C++ Functions
C++ Functions
Functions are used to perform certain actions, and they are important for reusing
code: Define the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute
code. But you can also create your own functions to perform certain actions.
Syntax
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use",
and will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it
is called:
Example
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Declaration: the return type, the name of the function, and parameters (if
any)
Definition: the body of the function (code to be executed)
void myFunction()
{ // declaration
// the body of the function (definition)
}
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
However, it is possible to separate the declaration and the definition of the function
- for code optimization.
You will often see C++ programs that have function declaration above main(), and
function definition below main(). This will make the code better organized and
easier to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Exercise:
void () {
cout << "I just got executed!";
}
int main() {
;
return 0;
}
Function Parameters
Information can be passed to functions as a parameter. Parameters act as variables
inside the function.
Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following example has a function that takes a string called fname as
parameter. When the function is called, we pass along a first name, which is used
inside the function to print the full name:
Example
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the function, it is called an argument. So, from the
example above: fname is a parameter,
while Liam, Jenny and Anja are arguments.
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter". From
the example above, country is an optional parameter and "Norway" is the default
value.
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
Note that when you are working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the arguments
must be passed in the same order.
Return Values
The void keyword, used in the previous examples, indicates that the function
should not return a value. If you want the function to return a value, you can use a
data type (such as int, string, etc.) instead of void, and use the return keyword
inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
In the examples from the previous page, we used normal variables when we passed
parameters to a function. You can also pass a reference to the function. This can be
useful when you need to change the value of the arguments:
Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
return 0;
}
Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Example Explained
The function (myFunction) takes an array as its parameter (int myNumbers[5]),
and loops through the array elements with the for loop.
When the function is called inside main(), we pass along the myNumbers array,
which outputs the array elements.
Note that when you call the function, you only need to use the name of the array
when passing it as an argument myFunction(myNumbers). However, the full
declaration of the array is needed in the function parameter (int myNumbers[5]).
Function Overloading
With function overloading, multiple functions can have the same name with
different parameters:
Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which have two functions that add numbers of
different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Try it Yourself »
Instead of defining two functions that should do the same thing, it is better to
overload one.
Example
int plusFunc(int x, int y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Note: Multiple functions can have the same name as long as the number and/or
type of parameters are different.
Recursion
Recursion is the technique of making a function call itself. This technique provides
a way to break complicated problems down into simple problems which are easier
to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:
Example
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the function just returns
0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and
returns the result.
Inline Functions
C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define
the function before any calls are made to the function. The compiler can ignore the
inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two
numbers –
#include <iostream>
using namespace std;
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
The inline keyword suggests that the compiler substitute the code within the
function definition in place of each call to that function.
In theory, using inline functions can make your program faster because they
eliminate the overhead associated with function calls. Calling a function requires
pushing the return address on the stack, pushing arguments onto the stack, jumping
to the function body, and then executing a return instruction when the function
finishes. This process is eliminated by inlining the function. The compiler also has
different opportunities to optimize functions expanded inline versus those that
aren't. A tradeoff of inline functions is that the overall size of your program can
increase.
Inline code substitution is done at the compiler's discretion. For example, the
compiler won't inline a function if its address is taken or if the compiler decides it's
too large.