Default Argument in C++ Language
Default Argument in C++ Language
Lets take a examples to explain Default Argument :-
Example - 1 A program of adding two numbers
OUTPUT
ENTER TWO NUMBER 3 4
SUM IS 7
Example - 2
Now we want to add three numbers so we pass 3 variable i.e add(a,b,c) as we seen in below
example but an error come after compile lets see what error...
Example-3
After compile one error got that is Extra parameter in call to add(int,int), Its means you are passing or more than 2 variable because we declared only two int i.e int add(int,int) and funtion define with 2
variable only i.e int add(int x, int y)
Example -4
Here we correct the above error by add 1more int in declaration statement i.e int add(int,int,int) and add 1 variable at the time of defining the function i.e int add(int x,int y,int z), lets see what happen after compile now.
Example -5
After compiling one more error occur i.e Too few parameters in call to 'add(int,int,int),its means you calling less value than at the time of declaration i.e you declared 3 variable (int add(int,int,int)
but you pass only 2 i.e add(a,b)
Example -6
Now we correct above error with help of default argument which provide C++ Language by
default i.e at the time of declaration C++ provide option (default argument ) that although we can't change function coding i.e function adding 3 variable but at the time function calling if we want
to pass only two and by default 3rd variable consider as zero so at time of declaration of function
we initializing 3rd int as int=0 as we seen in below example..Now whats happen while you calling two variable i.e add(a,b) then 'a' value assign in 'x' and 'b' value assign in 'y' but 3rd variable is not pass so by default z assign 0..
Example - 7
1- Its not necessary you can only pass 0 value but we make
add function so 0 is correct for us.
as zero then you have to initialize remaining all the variable as we seen in Example -8
Example - 8
we correct above error in below example..
default argument |
If this article is helpful to you then please like share.....thank you..
Comments
Post a Comment