2 min read
 // function to add two integers
 int add(int x, int y)               //function definition
 {
 int z;
  z=x+y;
 return z;
 }
 Void main()
 {
 int a,b,sum;
  cout<<"Enter values to be added";
 cin>>a>>b;
 sum=add(a,b);                  //function call
 cout<<"\n The sum is"<<sum;
 } 

Output

Enter values to be added
5
9
The sum is 14

As you have seen earlier we need 3 statements in order to make a function and execute it. In this program, we made a function named add (function definition) and call it in the program when needed.

Now you must be thinking we don’t have any function prototype in this, then how does compiler is working with it?

Because in the case when we define a function before main we don’t need any function declaration.

Types of parameters

Formal parameters:

The parameters that appear in the function definition and prototype are known as formal parameters. For example- in the given program x, y are formal parameters.

Actual parameters:

The parameters that appear in the function call are known as actual parameters. For example- in the given program a, b are actual parameters. They are also known as Arguments.

Types of Arguments

Arguments are of two types:

Default arguments:

c++ allows us to assign default value to any parameter in case, matching arguments are not passed in the function. The default values are specified at the time of function definition. For example: In the add function if the user don’t give both or any value to the actual parameters, a function can use its default value.

// function to add two integers
int add(int x=5, int y=9)               //function definition
{
 int z;
 z=x+y;
return z;
}
Void main()
{
int a,b,sum;
 cout<<"Enter values to be added";
cin>>a>>b;
sum=add();                     //function call
cout<<"\n The sum is"<<sum;
sum=add(a,b);                  //function call
cout<<"\n The sum is"<<sum;

}

Output

Enter values to be added
8
8
The sum is14               //with default values
The sum is 16              //actual values

Constant arguments

It is meant that the function cannot modify these arguments.If you pass a constant value to the function, then the function cannot modify the values as the values are constant.

For example: if we pass direct values to the function

 sum=add(7,8);           //function call 
Categories: Uncategorized

0 Comments

Leave a Reply