capypad
0 day streak
cpp / beginner
Snippet

Defining and Calling Functions

Functions are reusable blocks of code. You define them with a return type, name, and parameters. When called, they execute their code and optionally return a value. Functions help organize and reuse code.

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 << "Result: " << 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;
Calculate and return the sum of a and b
3
int result = add(3, 4);
Call function with arguments 3 and 4, store result
4
std::cout << "Result: " << result;
Display the calculated result