- Asked 2/10
- 2073 Shrawan · 2+2 marks
- 2072 Kartik · 4 marks
Default arguments and their syntax
Short answer
Default arguments provide predetermined values for function parameters so callers may omit trailing arguments. Syntax: return_type func(type p1, type p2=val, ...); defaults must be right-to-left. Only constants, global variables, or static expressions can be used.
What do you understand by default arguments? Write the syntax of default arguments.
A default argument is a value given to a function parameter in the function declaration. If the caller leaves that argument out, the compiler automatically uses the default value. If the caller supplies a value, the default is ignored.
Syntax
return_type function_name(type p1, type p2 = default_value, type p3 = default_value);
- Default values are given from right to left: once a parameter has a default, all parameters to its right must also have defaults.
- The default is written once, in the declaration (prototype) or in the definition if there is no prototype, not in both.
- Default values may be constants, global variables or expressions, but not local variables.
Example
#include <iostream>
using namespace std;
// w and h take default values
float volume(float l, float w = 1, float h = 1)
{
return l * w * h;
}
int main()
{
cout << volume(5) << endl; // 5*1*1 = 5
cout << volume(5, 4) << endl; // 5*4*1 = 20
cout << volume(5, 4, 3) << endl; // 5*4*3 = 60
return 0;
}
Valid: void f(int a, int b = 2, int c = 3);
Invalid: void f(int a = 1, int b, int c = 3); because b has no default but lies to the right of a defaulted parameter.
Advantage: one function can be called in several ways, which reduces the number of overloaded functions we must write.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Default arguments and function overloading · Object Oriented Programming, chapter 3 · asked 5×
- Display N characters using default arguments · Object Oriented Programming, chapter 3
- Default arguments in class template · Object Oriented Programming, chapter 9
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×