Function
Programming
What you need to know first 1 concepts, 1 layers
The requisite-knowledge inventory for this page, bottom-up: the primitives at the base, combined upward until you reach what this page assumes. Skim the layers you already own; start wherever the ground gets unfamiliar.
- base
- ↳you are here
This program demonstrates how to define and call functions in C++. Functions allow code reuse and modularity.
Implementation
#include <iostream>
int add(int x, int y) {
return x + y;
}
int main() {
int a = 5, b = 3;
std::cout << "a: " << a << std::endl;
std::cout << "b: " << b << std::endl;
std::cout << "Sum: " << add(a, b) << std::endl;
return 0;
} Function Definition
A function definition has the following syntax:
return_type function_name(parameter_list) {
// function body
return value;
} Key Concepts
- Function Declaration:
int add(int x, int y)- defines a function that takes two integers and returns an integer - Parameters:
xandyare function parameters - Return Statement:
return x + y;returns the computed value - Function Call:
add(a, b)invokes the function with arguments
Output
a: 5
b: 3
Sum: 8