Friday, 28 November 2014

What are default arguments in C++ with example

What are default arguments in C++:

The value that is provided in the declaration of the function itself is called as default argument.
These default values are assigned automatically to the function by the compiler.
We will look into the sample program below.

#include<iostream>
using namespace std; int Add (int iVal1, int iVal2, int x=0, int y=0) {     return (iVal1 + iVal2 + x + y); } int main() {     cout << Add(100, 150) << endl;     cout << Add(100, 150, 250) << endl;     cout << Add(160, 105, 295, 380) << endl;     return 0; }
In the above program there is no need to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.

Output of the above program is:
250

500

940
The default arguments should pass like  all subsequent arguments must have default value.
int Add (int iVal1, int iVal2, int x=0, int y=0);  // valid

int Add (int iVal1, int iVal2, int x=0, int y); // not valid

No comments: