default parameter
default parameter
What is a default parameter?
on a typical morning,you want to buy a milk tea,so you open your smartphone,and select your favorate flavor.After a monent,you decide to pay for it.At this point,your smartphone usually has options to let you choose sugar level.If you don't make a selection,your milk tea will be made with full sugar-this is just like a default parameter in programming.
How to use default parameter
Basic grammar
int add(int a=10,int b=10){
//if you don't pass any parameter,the fuction use a=10 and b=10 default
return a+b;
}
simple program block
int add(int a=1, int b=1) {
return a + b;
}
int main() {
int a, b;
cout << "Enter values for a and b(default:1 if not entered):";
cin >> a >> b;
cout<<add()<<endl; //Call without parameter
cout << add(a, b) << endl; //Call with parameters
}
output
Enter values for a and b(default:1 if not entered):1 2
2
3
Points to note
- Default parameters can only be specified in the function declaration (not repeated in the definition)
int add(int a=10,b=10)
int main(...){...}
int add(int a=10,b=10) //Invalid
//👇
int add(int a,b) //Valid
- Default parameters must be placed at the end of the parameter list
int add(int a=10,b) //Invalid
//👇
int add(int b,a=10) //Valid
- use constant and #define macros instead of assigning values to variables
#define s 10
int b=1;
int function(int a=s) //👍
int function(int a=1) //👍
int function(int a=b) //❌
this is all,thank you for reading

浙公网安备 33010602011771号