C Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the function.
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Two types of Parameter Passing to functions:
- Actual Parameters - parameters passed to function.
- Formal Parameters - parameters received by function.
There are two most popular ways to pass parameters.
1. Pass by Value: Values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller.
2. Pass by Reference: Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller.
The following function that takes a string of characters with color as parameter. When the function is called, we pass along a color, which is used inside the function to print all colours.
When a parameter is passed to the function, it is called an argument..
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Main Function:
The main function is a special function. Every C++ program must contain a function named main. It serves as the entry point for the program. The computer will start running the code from the beginning of the main function.
Types of main Function:
// Without Parameters
int main()
{
...
return 0;
}
// With Parameters
int main(int argc, char * const argv[])
{
...
return 0;
}
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 or float, etc.) instead of void, and use the return keyword inside the function: