C++ Functions
A function is a named block of code which you can call many times.
#include <iostream>
void greet() {
std::cout << "Hello from a function!\n";
}
int add(int a, int b) {
return a + b;
}
int main() {
greet();
std::cout << add(5, 7) << '\n';
}
Output
Hello from a function!
12
Declaration and definition
A function must be known before you call it. When the definition comes later, write a declaration (prototype) first. Prototypes are normally in header files.
#include <iostream>
int square(int n); // declaration
int main() {
std::cout << square(9) << '\n';
}
int square(int n) { // definition
return n * n;
}
Output
81
Pass by value
The function gets a copy. Changing the parameter does not change the original (we will use references for that).
#include <iostream>
void change(int x) {
x = 100;
std::cout << "inside: " << x << '\n';
}
int main() {
int n = 5;
change(n);
std::cout << "outside: " << n << '\n';
}
Output
inside: 100
outside: 5
Return values and multiple results
#include <iostream>
#include <string>
#include <tuple>
#include <utility>
std::pair<int, int> min_max(int a, int b) {
return {a < b ? a : b, a < b ? b : a};
}
auto describe(int n) { // the return type is found from the code
return std::to_string(n) + (n % 2 == 0 ? " is even" : " is odd");
}
int main() {
auto [low, high] = min_max(9, 4); // structured bindings (C++17)
std::cout << low << ' ' << high << '\n';
std::cout << describe(7) << '\n';
}
Output
4 9
7 is odd
Special function types
inline: a hint to put the code in place of the call.constexpr: can run at compile time.[[nodiscard]]: the compiler warns when the result is ignored.
#include <iostream>
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
int main() {
constexpr int f5 = factorial(5); // calculated while compiling
static_assert(f5 == 120);
std::cout << f5 << '\n';
}
Output
120
Rules
- Give a function one clear job and a verb name:
calculate_total,is_valid. - A function with a return type must return a value on every path (the compiler warns).
mainis special: it can not be called by you, and it returns 0 if you forget.
Note:
Pass big objects (like strings and vectors) by const reference, not by value. We learn that in the chapter about references. Next: C++ Function Overloading and Default Arguments.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |