C++ functions: Passing Arguments by Value

By default, the arguments are passed by value to parameters when invoking a function.

The power of a function is its ability to work with parameters. You can use max to find the maximum between any two int values. When calling a function, you need to provide argu­ments, which must be given in the same order as their respective parameters in the function signature. This is known as parameter order association. For example, the following function parameter order association prints a character n times:

void nPrint(char ch, int n)

{

for (int i = 0; i < n; i++)

cout << ch;

}

You can use nPrint(‘a’, 3) to print ‘a’ three times. The nPrint(‘a’, 3) statement passes the actual char parameter, ‘a’, to the parameter, ch; passes 3 to n; and prints ‘a’ three times. However, the statement nPrint(3, ‘a’) has a different meaning. It passes 3 to ch and ‘a’ to n.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *