Defining C++ functions
A function is a block of code that only runs when it is called. Functions are usually defined and used to perform certain actions, and they can be called anytime when needed; therefore, they are reusable code. Through the use of functions, we can avoid redundant code, reducing the risk of code inconsistency and the chance of program bugs.
Defining functions with or without parameters
To define a function, you should specify the name and return type of the function, followed by a pair of parentheses. Presented here is a function that has no parameter and a void
return type:
void DisplayLabel(){ std::cout << "The result of 1 + 2 is "; }
You can pass data as parameters into a function, and the function parameters are placed in between the parentheses. Presented here is a function that has two int
parameters and returns the addition of the two input values as the result:
int Add(int a, int b){ return...