Default Argument in C++





In C++ programming, you can provide default values for function parameters.

The idea behind default argument is simple. If a function is called by passing argument/s, those arguments are used by the function.

But if the argument/s are not passed while invoking a function then, the default values are used.

Example:

#include<iostream>
using namespace std;

//default value for b

void add(int a, int b=10){
 int sum = a + b;
 cout<<"RESULT = ";
 cout<< sum<< endl;
}
int main() {
 add(10);
 add(20,10);
 return 0;
}
OUTPUT:
RESULT = 20
RESULT = 30

First function call will use b's default value and produce the output.
In second function call, since you are providing value for b , so now b will use this passed value.
Points to Remember:

1. You cannot have a default argument followed by non-default argument.
//correct
void add(int a,int b);
//correct
void add(int a,int b=20);
//incorrect
void add(int a=10,int b);

2. If you default an argument, then you will have to default all the subsequent arguments after that.
//correct
void add(int a,int b=20);
//incorrect
void add(int a,int b=20,int c);
//correct
void add(int a,int b=20.int c=5);

3. No matter how you use default arguments, a function should always be written so that it serves only one purpose.
If your function does more than one thing or the logic seems too complicated, you can use Function overloading to separate the logic better.

4. Default values are passed to argument in the function prototype
void add(int ,int=20);
    OR
void add(int a ,int b=20);
                    

Next topic is OOP Concepts





 




Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved