cpp / beginner
Snippet
Creating Custom Functions
Functions are reusable blocks of code that perform specific tasks. The add function takes two parameters and returns their sum. The greet function takes a name parameter but does not return anything (void). Functions help organize code and avoid repetition.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>using namespace std;int add(int a, int b) {int result = a + b;return result;}void greet(string name) {cout << "Hello, " << name << "!" << endl;}int main() {int sum = add(5, 3);cout << "5 + 3 = " << sum << endl;greet("World");return 0;}
Breakdown
1
int add(int a, int b)
Function declaration with two int parameters and int return type
2
return result;
Sends the computed value back to the caller
3
void greet(string name)
Function that takes a string but returns nothing
4
int sum = add(5, 3)
Calling function and storing returned value
5
greet("World")
Calling function with a string argument