Programmingoneonone is known for sharing best programming knowledge.

Default arguments in function in c++ programming

In this post, you will learn about the default arguments in function in c++ programming and learn how to use and call the default arguments in programming.


default arguments in c++ programming, learn c++ programming
learn c++ programming


Default arguments:

if we give the value to the variables at the definition time of the function is called default arguments.

Example:
                int add(int x, int y, int z=0, int a=10 )
                {

                    code for execution;


                 }


here in the above example, the value for the z and a is default 0 and 10.

here in the above example, we can call the add function by three types.

add(10,20);
               
if we call the above function like add(10,20); then the default value for the z and a is included by the compiler. means value for x=10, y=20, z=0, a=10.

add(10,20,30);

if we call the above function like add(10,20,30); then the value for z is now 30 and the default value for a is used by the compiler.

add(10,20,30,40);

if we call the above function like add(10,20,30,40); then the value for z and a is now 30 and 40. now the default value for the z and a is not used by the compiler.

     { methods of calling the function = [no of default agruments + 1] }

in the above example, there are two default arguments so the no of ways by which we can call the function is = 2+1= 3.

Example program using the default arguments in a function:

        #include <iostream>
      
        int add(int a, int b, int c=60, int d=0)
        {

              std::cout<<"\n addition of a,b,c and d ="<<a+b+c+d;

        }

        int main()

        {
              
           add(10,20);
           add(10,20,30);
           add(10,20,30,40);

           return 0;


        }



so, I think now you understood what is default arguments and how it can make difference at the time of function call.

"Please share this knowledge as much possible as you can and also comment me your queries and questions related to this topic. I will really grateful to help you."

No comments:

Post a Comment