capypad
0 day streak
cpp / beginner
Snippet

Creating Reusable Code with Functions

Functions are reusable blocks of code that perform specific tasks. The add function takes two integers, adds them, and returns the result. The printMessage function takes a string and displays it but returns nothing (void). Functions help avoid code repetition and make programs easier to organize and maintain.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
int add(int a, int b) {
return a + b;
}
 
void printMessage(std::string msg) {
std::cout << msg << std::endl;
}
 
int main() {
int result = add(5, 3);
printMessage("The sum is: ");
std::cout << result << std::endl;
 
return 0;
}
Breakdown
1
int add(int a, int b) {
Function declaration: takes two integers and returns an integer
2
return a + b;
Returns the sum of parameters a and b
3
void printMessage(std::string msg) {
Function with no return value (void) taking a string parameter
4
int result = add(5, 3);
Calling add function with values 5 and 3, stores result in variable
5
printMessage("The sum is: ");
Calling printMessage with a string argument