You are on page 1of 12

JAIPUR NATIONAL UNIVERSITY

SUBJECT :- OOPS USING C++


TOPIC :- FUNCTION PARAMETER PASSING,
DEFAULT ARGUMENTS
UDER THE GUIDENCE OF :- Ms. Amita Kashyap
STUDENT NAME :- Girish Singh Sagar
INTRODUCTION

Default Arguments (Parameters)

In C++ programming, we can provide default values


for function parameters.
If a function with default arguments is called
without passing arguments, then the default
parameters are used.
However, if arguments are passed while calling the
function, the default arguments are ignored.
DEFAULT ARGUMENTS IN C++

A default argument is a value provided in a function


declaration that is automatically assigned by the compiler
if the caller of the function doesn't provide a value for the
argument with a default value. Following is a simple C++
example to demonstrate the use of default arguments.
EXAMPLE :-

#include<iostream>
using namespace std;
int add(int x=2, int y=4, int z=6)
{
return (x+y+z);
}
int main()
{
cout<<add()<<endl;
cout<<add(10)<<endl;
cout<<add(10,20)<<endl;
cout<<add(10,20,30)<<endl;
return 0;
}
RULES OF DEFAULT ARGUMENTS

As you have seen in the above example that I have


assigned the default values for all three arguments a, b and
c during function declaration. It is up to you to assign
default values to all arguments or only selected arguments
but remember the following rule while assigning default
values to only some of the arguments:
If you assign default value to an argument, the
subsequent arguments must have default values
assigned to them, else you will get compilation error.
EXECUTION :-
OUTPUT :-
LETS SEE SOME VALID AND INVALID
CASES

int sum(int a=10, int b=20, int c=30);

int sum(int a, int b=20, int c=30);

int sum(int a, int b, int c=30);


FOLLOWING FUNCTION
DECLARATIONS ARE INVALID
1. Here a has default value assigned, all the
arguments after a (in this case b and c) must have default
values assigned, if not then it is invalid.

int sum(int a=10, int b, int c=30);


2. Here b has default value assigned, all the
arguments after b (in this case c) must have default values
assigned, if not then it is invalid.

int sum(int a, int b=20, int c);


3. Here a has default value assigned, all the
arguments after a (in this case b and c) must have default
values assigned, b has default value but c doesn't have,
that’s why this is also invalid

int sum(int a=10, int b=20, int c);


Thank You Everyone…

You might also like