C++ Function Parameters

October 27, 2015 Posted by WithU Technologies
Parameters corresponds with the local variables of main() function which create link between the parameter of declared function and the local variables of main() function.

#include <iostream>
using namespace std;

int displayNumber(int x){ //Single integer parameter is used

      cout<<x;    // Outputs 12

}

int main(){

      displayNumber(12);   // value for x is defined here

}

·         It takes one integer parameter and prints its value.

·         After defining the parameter, we can pass the corresponding arguments when the displayNumber() function is called by the main() function.

·         The value 12 is passed to the function as an argument, and assigned to the formal parameter of the function i.e. x.

One function with different arguments:

#include <iostream>
using namespace std;

int displayNumber(int x){ //Single integer parameter is used

      return x/2;   //different arguments to the same function

}

int main(){

      cout<<displayNumber(12)<<endl;   // value for x is defined here and outputs 6

      cout<<displayNumber(14)<<endl;   // value for x is defined here and outputs 7

      cout<<displayNumber(2)<<endl;   // value for x is defined here and outputs 1     

     return 0;

}
·         Here one function is declared and defined with an integer parameter named x and then returns its value, divided by 2.

·         Then we use that same function with three different arguments which outputs three different values.

Default Arguments:

So, we are now fully aware with the process to use parameters in functions which are manually defined and declared.

But, we can also provide default value to the parameters, in case the main() function did not provide any value.

We can specify a default value for each of the last parameter. If the corresponding value is missing during the calling of that function, it uses the default provided.

#include <iostream>
#include <stdlib.h>
using namespace std;

int add(int a, int b=5){   

      int output;

      output = a+b;

      return(output);

}

int main(){

int x= 10;

int y = 5;

int result;

// Output with y is 15

result=add(x, y);

cout<<result<<endl;

// Output without y is also 15 due to same default value

result=add(x);

cout<<result<<endl;

return 0;

}

Here we use default value of b as 5, which is the last parameter and when the second call for function does not pass a value for the second parameter at that time it uses the default value of b, which is 5.