cpp / beginner
Snippet
Creating Reusable Functions
Functions are reusable blocks of code that perform a specific task. A function definition includes a return type (int), a name (add), and parameters in parentheses. Parameters act as inputs the function receives when called. The return statement sends a value back to the caller. To use a function, call it by name with arguments inside the parentheses. The function then returns the result which can be stored in a variable.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>int add(int a, int b) {return a + b;}int main() {int result = add(3, 4);std::cout << "3 + 4 = " << result << std::endl;return 0;}
Breakdown
1
int add(int a, int b) {
Function definition: returns int, takes two int parameters
2
return a + b;
Returns the sum of parameters a and b
3
int result = add(3, 4);
Calls function with arguments 3 and 4, stores returned value
4
std::cout << "3 + 4 = " << result << std::endl;
Prints the calculated result