c sharp Logo

Function Parameters


Function parameters in C++ are the variables that are passed to a function when it is called. Parameters can be used to provide input to a function or to receive output from a function.

To declare a function parameter, you use the following syntax:

data_type parameter_name

 

The data_type specifies the type of the parameter. The parameter_name is the name of the parameter.

For example, the following function declaration has two parameters, one of type int and one of type float:

void add(int x, float y) {

  // function body

}

 

When you call the add() function, you must pass two arguments to the function, one of type int and one of type float. For example:

add(10, 2.0);

 

The values of the arguments are assigned to the function parameters x and y respectively.

Function parameters can also be used to return output from a function. To do this, you declare the parameter with the & operator. This tells the compiler that the parameter is a reference to a variable.

For example, the following function declaration has a return parameter of type int&:

int& max(int& x, int& y) {

  // function body

}

 

This function returns a reference to the larger of the two integers that are passed to it as parameters.

To call the max() function, you must pass two references to integer variables to the function. For example:

int a = 10;

int b = 20;

 

int& max_value = max(a, b);

 

The max() function will return a reference to the larger of the two integers a and b. The max_value variable will now refer to the larger integer.

Function parameters are a powerful tool that can be used to make your code more reusable and maintainable. By understanding how to use function parameters, you can write more efficient and effective C++ code.

Here are some additional examples of using function parameters in C++:

// Pass a parameter by value.

void print_value(int value) {

  std::cout << value << std::endl;

}

 

// Pass a parameter by reference.

void increment(int& value) {

  value++;

}

 

// Return a value from a function.

int add_values(int x, int y) {

  return x + y;

}

 

int main() {

  int a = 10;

  int b = 20;

 

  // Pass a parameter by value.

  print_value(a);

 

  // Pass a parameter by reference.

  increment(b);

 

  // Return a value from a function.

  int sum = add_values(a, b);

 

  std::cout << sum << std::endl;

 

  return 0;

}

 

Output:

10

21

30