C++ Functions
A function is a named block of code that does one job. You can call it as many times as you like.
Creating and Calling a Function
Example
#include <iostream>
using namespace std;
void showLine() {
cout << "--------------------\n";
}
int main() {
showLine();
cout << " Workownix Receipt\n";
showLine();
return 0;
}-------------------- Workownix Receipt --------------------
A function must be declared before it is called. Either write it above main, or put a declaration like void showLine(); at the top.
Parameters and Return Values
Example
#include <iostream>
using namespace std;
double average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
bool isEven(int n) {
return n % 2 == 0;
}
int main() {
cout << average(70, 85, 90) << "\n";
cout << boolalpha << isEven(14) << "\n";
return 0;
}81.6667 true
Default Arguments
A parameter can have a default value that is used when you leave it out:
Example
#include <iostream>
#include <string>
using namespace std;
void greet(string name, string city = "Karachi") {
cout << name << " from " << city << "\n";
}
int main() {
greet("Ayesha");
greet("Usman", "Multan");
return 0;
}Ayesha from Karachi Usman from Multan
Function Overloading
Several functions can share a name if their parameter lists are different:
Example
int area(int side) { return side * side; }
int area(int length, int width) { return length * width; }
// area(5) gives 25, area(4, 6) gives 24Pass by Value and Pass by Reference
By default, C++ passes a copy of the argument. Add & to the parameter type to pass a reference, so the function works on the original variable:
Example
#include <iostream>
using namespace std;
void addCopy(int x) {
x += 10;
}
void addRef(int& x) {
x += 10;
}
int main() {
int points = 5;
addCopy(points);
cout << points << "\n";
addRef(points);
cout << points << "\n";
return 0;
}5 15
| Style | Parameter | Changes the original? |
|---|---|---|
| By value | int x | No |
| By reference | int& x | Yes |
| By const reference | const string& s | No, and it avoids copying |
For big objects like strings and vectors that the function only reads, use const references (const vector<int>& v). It is faster because nothing is copied.
Recursion
Example
int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}
// power(2, 10) gives 1024Exercise
Exercise
Which parameter lets a function change the caller's variable directly?
