cpp / beginner
Snippet
Defining and Calling Functions
Functions are reusable blocks of code that perform specific tasks. They can accept parameters and return values. The return type void means the function does not return a value. Functions must be declared before they are called in main.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>using namespace std;int add(int x, int y) {return x + y;}void greet(string name) {cout << "Hello, " << name << "!" << endl;}int main() {int result = add(10, 20);cout << "Result: " << result << endl;greet("World");greet("C++");return 0;}
Breakdown
1
int add(int x, int y)
Function that takes two integers and returns their sum
2
return x + y;
Sends the computed value back to the caller
3
void greet(string name)
Function with no return value that accepts a string parameter
4
int result = add(10, 20);
Calls add and stores the returned value in result
5
greet("World");
Calls greet with the string argument "World"