Functions and Parameters
💻 C++Break programs into functions and understand pass-by-value and pass-by-reference.
Functions make code reusable and testable. In C++ you also control whether a parameter is copied or referenced.
- Define and call functions.
- Use pass-by-reference.
- Provide default arguments.
A Function
Declare the return type, name and parameter types. A function must be declared before it is called.
#include <iostream>
int add(int a, int b) {
return a + b;
}
void greet(const std::string& name) {
std::cout << "Hello, " << name << "\n";
}
int main() {
std::cout << add(3, 4) << "\n";
greet("Amina");
return 0;
}Pass by Reference
By default, arguments are copied. For large objects, pass by const reference to avoid the copy. Use a non-const reference when the function must change the caller's value.
void addScore(int& score, int points) {
score += points;
}
int score = 60;
addScore(score, 10); // score is now 70Default Arguments
A parameter can have a default value. Defaults must come after parameters without defaults.
double priceWithVat(double price, double rate = 0.075) {
return price * (1 + rate);
}Practice
- Write a function that returns the larger of two numbers.
- Write a function that doubles a number through a reference.
- Add a default argument to a greeting function.
Hands-on exercise
Write two functions:
1. char grade(int score) returning A to F.
2. double average(const std::vector<int>& scores).
Print the grade and average for three scores.
Recap
Functions name work. Pass small values by value and large or mutable values by reference.
Example
#include <iostream>
int add(int a, int b) {
return a + b;
}
void greet(const std::string& name) {
std::cout << "Hello, " << name << "
";
}
int main() {
std::cout << add(3, 4) << "
";
greet("Amina");
return 0;
}
Exercises
1. char grade(int score) returning A to F.
2. double average(const std::vector<int>& scores).
Print the grade and average for three scores.
Expected Output
Grade B and Average 74.6667
Lesson Nav
C++ Course
0/9 lessons completed
- 1 Your First C++ Program Tutorial
- 2 Variables, Types and Input Tutorial
- 3 Conditions and Loops Tutorial
- 4 Functions and Parameters Tutorial
- 5 Arrays and Vectors Tutorial
- 6 Pointers and References Tutorial
- 7 Classes and Objects Tutorial
- 8 The STL: Containers and Algorithms Tutorial
- 9 Project: A Console Grade Book Project