C++ Functions
A Function is a block of code that can be reused many times throughout the program. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can write a single line to call the function which makes our code more compact.
Syntax:
Functions are further subdivided into user-defined and pre-defined
Let us look into each of them in detail.
User-defined functions
A user-defined function is a function provided by the user of a program or environment, in a context where the usual assumption is that functions are built into the program or environment. User-defined functions are written by us for our own requirements.
Consider a program to swap two numbers.
But what if we had to swap multiple numbers, it would become a tedious job. Instead, we can just put the swapping piece of code in a function, and give it a unique name following the following rules
- Don't use a C++ keyword in your function name.
- They must start with a letter or an underscore: _.
- They should be lowercase.
- They can have numbers.
- They can be any length (within reason), but keep them short.
And then we pass the numbers to be swapped as actual parameters.
When a function is called, the values (expressions) that are passed in the call are called the arguments or actual parameters (both terms mean the same thing).
Pass by Value and Pass by Reference
In the above code we are calling the swap function and we are passing the actual arguments by reference.
call by reference
Recall we learned in C++ data types |&| is used to refer to the address of the variable. To understand what pass by reference is let us execute the same program using pass by value where the actual parameters in the function call are simply copied to the formal parameters.
There is no change in the swapped values this is because whatever we performed in the function was applicable only to the formal parameters and not to the actual parameters therefore we need to use the call by reference method when we wish to change the values of the actual parameters.
call by value for the swap function
The call by reference method of passing parameters to a function copies the reference of an actual parameter into the formal parameter. Inside the function, the reference is used to access the actual parameter used in the call. This means that changes made to the formal parameter affect the passed actual parameter.
The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function