capypad
0 day streak
cpp / beginner
Snippet

Functions: Breaking Code into Reusable Blocks

Functions are reusable blocks of code that perform specific tasks. They can accept parameters (inputs) and return a value (output). The add function takes two integers, adds them together, and returns the sum. Calling add(3, 4) gives us 7.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
#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 a and b to the caller
3
int result = add(3, 4)
Calls the function with arguments 3 and 4, stores the returned value