c sharp Logo

Functions


A function in C++ is a block of code that performs a specific task. Functions are used to organize code into reusable modules and to make code more modular and maintainable.

To declare a function in C++, you use the following syntax:

return_type function_name(parameter_list) {

  // function body

}

 

The return_type specifies the type of data that the function returns. The function_name is the name of the function. The parameter_list is a list of parameters that the function accepts. The function body is the block of code that the function executes.

Functions can be called from anywhere in your program. To call a function, you use the following syntax:

function_name(arguments);

 

The arguments are the values that you pass to the function as parameters.

Example

The following example shows a simple function that adds two numbers and returns the result:

int add(int x, int y) {

  return x + y;

}

 

int main() {

  int sum = add(10, 20);

 

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

 

  return 0;

}

 

Output:

30

 

You can also use functions to perform more complex tasks, such as sorting a list of numbers or finding the maximum value in an array.

Function overloading

Function overloading allows you to define multiple functions with the same name, but with different parameter lists. This can be useful for defining functions that perform the same basic task, but with different data types or numbers of parameters.

For example, the following code shows two overloaded functions named max():

int max(int x, int y) {

  if (x > y) {

    return x;

  } else {

    return y;

  }

}

 

double max(double x, double y) {

  if (x > y) {

    return x;

  } else {

    return y;

  }

}

 

int main() {

  int max_int = max(10, 20);

  double max_double = max(1.0, 2.0);

 

  std::cout << max_int << std::endl;

  std::cout << max_double << std::endl;

 

  return 0;

}

 

Output:

20

2

 

When you call the max() function, the compiler will choose the appropriate overloaded function based on the data types of the arguments that you pass to the function.

Conclusion

C++ functions are a powerful tool that can be used to organize your code, make it more reusable and maintainable, and perform complex tasks. By understanding how to use functions, you can write more efficient and effective C++ code.