Positional and Default ArgumentsPositional and Default Arguments

Positional arguments are a way of passing values to a function in a specific order based on the function's signature.
They are called "positional" because the values are associated with parameters according to their positions in the parameter list of function signature. The position of each argument determines which parameter it corresponds to.
We have already covered positional arguments in the previous section. However, let's provide an additional example to enhance our understanding:



You can conduct a small experiment: change the order of passing arguments to the function (use divide (y, x) instead of divide(x, y)), and you will see that the result has changed. This is precisely the essence of positional arguments: the order of passing parameters to the function is important, directly affecting its result.

Default arguments

Default arguments in C++ allow you to specify default values for function parameters. When you provide default values for parameters in a function declaration, it means that if a caller does not explicitly pass an argument for that parameter when calling the function, the default value will be used instead. You can provide a default value by simply instantiating the required argument with some value in the function signature.

Let's consider an example based on our divide() function:



Code Description
  • The divide function is defined with three parameters:
  • - float a: The numerator.
    - float b: The denominator.
    - bool divideByZero = false: An optional parameter that, when set to true, allows division by zero.
  • Inside the divide function:
  • - It first checks whether b is equal to zero and divideByZero is set to false. If this condition is met, it prints an error message stating that division by zero is not allowed and returns 0.
    - If b is equal to zero and divideByZero is set to true, it returns a value (a / 0.0001) that avoids division by zero without displaying an error message.
    - If none of the above conditions are met, it performs the division of a by b and returns the result.

    We can see that divideByZero argument has a specified false default value, and we can ignore it when calling the function. But if we want to avoid an error and continue the calculation, we can set divideByZero=true at the end of the parameter list.


    It is important that all default arguments are located after the positional ones in the list of parameters. Otherwise, the compiler will throw an error.


    What will be the result of executing the following code

    Select the correct answer

    Everything was clear?

    Section 2. Chapter 1