Default Argument in C++

Advertisements

C++ Default Argument

A default argument is a function argument that has a default value provided to it. If the user does not supply a value for this argument, the default value will be used. If the user does supply a value for the default argument, the user-supplied value is used.


	Note : Only the trailing arguments can have default values and therefore
	we must add default values form right-to-left.

Some examples of function declaration with default values are:

int Add(int x, int y, int z=30);   //Valid
int Add(int x, int y=20, int z=30);   //Valid
int Add(int x=10, int y=20, int z=30);   //Valid
  
int Add(int x=10, int y, int z);   //Invalid
int Add(int x=10, int y, int z=30);   //Invalid

Example of default argument value


	#include<iostream.h>
	#include<conio.h>

	int Add(int x, int y=20, int z=30)
	{

		return x + y + z;

	}


	void main()
	{

		int rs;

		rs = Add(5);
		cout<<"\n\tThe sum is : "<<rs;

		rs = Add(4,8);
		cout<<"\n\tThe sum is : "<<rs;

		rs = Add(7,3,4);
		cout<<"\n\tThe sum is : "<<rs;

	}

	Output :

		The sum is : 55
		The sum is : 42
		The sum is : 14

         

Advertisement