cpp / beginner
Snippet
Functions: Returning Values
Functions can take input values, process them, and return a result. The return type is declared before the function name. The return statement sends the computed value back to the caller. In main(), we store the returned value in a variable and display it.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>int add(int a, int b) {return a + b;}int main() {int result = add(5, 3);std::cout << "5 + 3 = " << result << std::endl;return 0;}
Breakdown
1
int add(int a, int b)
Function declaration: returns int, takes two int parameters
2
return a + b;
Returns the sum of a and b to the caller
3
int result = add(5, 3);
Calls function with 5 and 3, stores returned value (8)