CKTIS / C++
Functions and parameters
A function describes an operation called with arguments. Learn the difference between declarations and definitions, parameters and arguments, and passing by value versus passing by reference.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
int add(int a, int b);
int add(int a, int b) { return a + b; }
int result = add(2, 3);A function separates an operation that you can invoke with an expression such as add(2, 3). The declaration int add(int a, int b); supplies its name, return type, and parameter types. The definition int add(int a, int b) { return a + b; } also supplies its body; it is a declaration too. A declaration must be available at an ordinary call site such as the one in the example.
A parameter, such as a in add, is declared in a function declaration’s parameter list, even if the declaration has no body. A parameter can be unnamed, even in a definition. An argument is an expression supplied at a call, such as number or 3. Arguments initialize the corresponding parameters. An empty list () means there are no parameters.
When passing int by value, as in add, the parameter is a separate object: changing it does not change the caller's integer. The parameter int& value binds to an existing object, so ++value in increment changes number. A parameter of type const int& allows reading the bound object but not modifying it through that reference.
return ends function execution and transfers control to the caller; return a + b; supplies the result. The type void means there is no result value. In an ordinary value-returning function, ensure that every path reaching the end returns a result: flowing off the body without returning causes undefined behavior. main is a special exception.
This entry targets C++23. The supplied site publishes an evolving working draft, not a frozen C++23 text; this explanation is limited to rules applicable in C++23. A repository compiler flag does not attest to the production environment.
Examples
#include <iostream>
int add(int a, int b);
void increment(int& value) {
++value;
}
int add(int a, int b) {
return a + b;
}
int main() {
int number = 4;
int result = add(number, 3);
increment(number);
std::cout << result << ' ' << number << '\n';
return 0;
}
Result
7 5
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.