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


arguments in c,default arguments in c++



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)

arguments in c,default arguments in c++

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.

arguments in c,default arguments in c++



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)


arguments in c,default arguments in c++


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.. 

arguments in c,default arguments in c++




Example - 7

1- Its not necessary you can only pass 0 value but we make 
 add function so 0 is correct for us.

 2- Here remember that we can't declared as int add(int,int=0,int)  because if you initialize 2nd variable
as zero then you have to initialize remaining all the variable as we seen in Example -8



arguments in c,default arguments in c++


Example - 8


we correct above error in below example..

arguments in c,default arguments in c++
default argument
If this article is helpful to you then please like share.....thank you..

Comments

Popular posts from this blog

Notepad, Wordpad and Paint

O LEVEL- INTERNET TECHNOLOGY & WEB DESIGN

O LEVEL- INTERNET TECHNOLOGY & WEB DESIGN