Course Content
C++ Functions
C++ Functions
Positional 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.
main
#include <iostream> // Function that takes two positional arguments float divide(float a, float b) { if (b == 0) { std::cout << "Error: Division by zero is not allowed" << std::endl; return 0; } return a / b; } int main() { float x = 8; float y = 4; // Calling the 'divide' function with two positional arguments float result = divide(x, y); std::cout << "The result is: " << result << std::endl; }
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:
main
#include <iostream> // Added the third default argument with specified value float divide(float a, float b, bool divideByZero = false) { if (b == 0 && !divideByZero) { std::cerr << "Error: Division by zero is not allowed." << std::endl; return 0; } else if (b == 0 && divideByZero) return a / 0.0000001; else return a / b; } int main() { float result1 = divide(51, 0.0, true); // Division by zero allowed std::cout << "Allowed: " << result1 << std::endl; float result2 = divide(7.0, 0.0); // Default behavior (Error message) std::cout << "Default: " << result2 << std::endl; }
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.
Note
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.
Thanks for your feedback!