C++ Passing Function Arguments and Returning Values

A function simply runs code defined inside its body. In addition to that, a function can also take inputs and return an output(result). The ability to take inputs (arguments/parameters) makes it very useful and flexible.

Without that, a function would be just a piece of tool to execute some static code not having the ability to process external inputs.

Function Parameters

Parameters are the additional inputs that a function can accept. Defining parameters is optional and depends on the requirements of the function.

The parameters are defined as a comma-separated list of variables inside the parenthesis.

General syntax of function with parameter

return_type function_name(data_type1 param1, data_type2 param2, data_type3 param3, …) {
  /* function body where param1, param2, etc. will be available for use… */
}
  • Parameters are defined inside the parenthesis of the function definition and are separated by commas.
  • Declaring a parameter is very similar to declaring a variable. The same rules apply to both.
  • We can define as many parameters as needed.
  • All parameters can have different data types in any order. Such as:
void myfunc(int num, char ch, int a, float pi) {
  /* function body */
}

Example of a function that takes two parameters

void add(int a, int b) {
  /* parameters a, b, are local to the add function */
  int c;
  /* use the parameters to do the processing */
  c = a + b;
  cout << "The sum of " << a << "and" << b << "is" << c;
}

The above function expects two values to be passed upon invoking/calling it. It will then use those values to print the result.

Function Arguments

After we define the function parameters, it becomes ready to accept external inputs.

We can pass these required inputs/data to a function when we invoke/call that function. These inputs are known as arguments.

If we invoke the add function defined above, we will have to pass two arguments inside the parenthesis.

add(3, 5);

/* Output will be: The sum of 3 and 5 is 8 */

We can also pass arguments as variables.

int num1 = 3, num2 = 5;
/* call add() by passing the variables: num1 and num2 */
add(num1, num2);

The main difference between arguments and parameters is that we use the term “argument” for the values we pass while calling the function.

Whereas, the term “parameter” is used when we talk about the function definition.

Matching the Function Parameters and Arguments

The arguments that we pass to a function must match the parameters. The data type and the number of arguments must be identical to the parameters in the function definition.

If we have a function as:

void mul(int a, int b) {
  /* function body */
}

And few variables in main() as below,

int num1 = 3, num2 = 5, num3 = 10, array[20];
char ch = 'a';

Then trying to run the following lines of code will throw errors:

mul(num1);
/* [Error] too few arguments to function 'int add(int, int)' */
mul(num1, num2, num3);
/* [Error] too many arguments to function 'int add(int, int)' */

When we pass data that has a different type from the parameter definition, the compiler tries to implicitly convert the argument and match both types.

/* No error as the character is auto-converted to an integer by the compiler. But the results will be unexpected. */

mul(num1, ch);

/* If we have a type that is not convertible to the one in the parameter definition, an error will be thrown.

[Error] invalid conversion from 'int*' to 'int' [-fpermissive]
Because arrays cannot be converted to a simple integer.
*/
mul(num1, array);

Scope of Parameters and Arguments

It is important to note that a parameter’s scope is different and independent of the argument’s scope.

When passing an argument to a function, a copy of its value is made for the function parameter.

Example:

void myfunc(int val) {
  /* 'val' is only available inside myfunc() */
  /* 'val' is a separate copy of the passed argument */
}
void main() {
  /* num is only visible inside main() unless it is explicitly passed as an argument to a function, as in myfunc() */
  int num = 2;
  /* any modification to 'num' inside myfunc() doesn't change the 'num' variable in main() */
  myfunc(num);
}

Default Parameters

A function can specify parameters with default values. These default values are only used if any required argument is not passed to the function.

void add(int a = 0, int b = 0) {
  /* a and b have 0 as their default values */
  cout << "Result is" << a + b;
}

Now there won’t be any error if we pass arguments less than the required amount.

add();
/* a=0, b=0 : Result is 0 */
add(3);
/* a=3, b=0 : Result is 3 */
add(3, 5);
/* a=3, b=5 : Result is 8 */

The default parameters must be defined to the rightmost side of the function parameters, otherwise, an error will be thrown as it leads to ambiguity.

/* invalid */
int add(int a = 0, int b, int c) {}
/* invalid */
int add(int a, int b = 0, int c) {}
/* valid – default parameters to the right */
int add(int x, int y, int z = 5) {}
/* valid – default parameters to the right */
int add(int x, int y = 0, int x = 5) {}

Returning Values from a function

A function usually takes some input, processes it, and then provides output as the result. This is known as returning a value from a function.
Every function definition must specify the data type of the value to return(called the return type).

return_type function_name(optional parameters) {
  data_type variable;
  return variable;
}

The data type of the variable that is returned must match the return type in the function definition.

int add(int a, int b) {
  int c = a + b;
  /* c is an int and it matches the return type of the function */
  return c;
}

Using the “return” keyword terminates the function and returns a value.

The value that we return can be accessed or stored from the place where the function was called.

void main() {
  int res;
  /* store the returned value to a variable */
  res = add(3, 5);
  /* res is now 8 */
  /* we can also use the returned value directly just like any other variable */
  cout << ”Sum of 3 and 5 is“ << add(3, 5);
}

If we are not returning any value from a function, the void type must be used as below.

void print(int num) {
  cout << "The number to print is" << num;
}

Function Signature and Declaration

The first line of a function’s definition contains important specifications like return type, function name, list of parameters.

It is known as the function’s signature as it uniquely identifies a function. Also, no two functions can have the same signature.

So, if we have a function as:

int add(int a, int b) {
  /* function body */
}

Then its signature will be:

int add(int a, int b);
/* we can also omit the parameter names as below */
int add(int, int);

Function Declaration

If a function is defined after main(), it must be declared otherwise scope errors will be thrown. Declaring a function just requires us to specify its signature before main(). It allows the compiler to identify the function.

/* function declaration( not required if function definition is placed above main ) */
int add(int, int);
void main() {
  add(3, 5);
}
/* function definition */
int add(int a, int b) {
  return a + b;
}

Points to Remember

  • Function Parameters are the inputs that a function can accept. A function can define any number of parameters.
  • Values passed to an invoked function are called function arguments.
  • The arguments passed to a function must match the number and type of the parameters.
  • Both the arguments and parameters of a function are specified inside the parenthesis.
  • The return keyword of a function is used to return a value from a function. The returned value can be stored inside a variable or used directly inside expressions.
  • A function’s signature uniquely identifies a function. It is used in declaring a function.
Back to: Learn C++ Programming > Function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.