Home >Backend Development >C++ >How to use functions in C++?

How to use functions in C++?

PHPz
PHPzOriginal
2024-04-12 13:36:121065browse

Using Functions in C A function is a reusable block of code used to increase code reusability and modularity. A function declaration specifies the function name, parameter types, and return type. The function definition provides the implementation of the function body. A function is called by using its name and passing the appropriate parameters.

C++ 中如何使用函数?

Using functions in C

A function is a block of code that can be used repeatedly in a program. It can improve the code reusability and modularity. In C, the syntax of a function is as follows:

return_type function_name(parameter_list) {
    // 函数体
}

where:

  • return_type is the type of value returned by the function. void if the function returns no value.
  • function_name is the name of the function.
  • parameter_list is the parameter list of the function, used to pass parameters to the function.

Function declaration and definition

Functions must be declared before they can be used. The function declaration specifies the name, parameter type and return type of the function. The syntax is as follows:

return_type function_name(parameter_list);

The function definition provides the implementation of the function body. The syntax is as follows:

return_type function_name(parameter_list) {
    // 函数体
}

Function call

To call a function, just use its name and pass the appropriate parameters, for example:

int sum(int a, int b) {
    return a + b;
}

int main() {
    int result = sum(10, 20);  // 调用 sum() 函数
    return 0;
}

Practical case

Let Let's write a C function that calculates the greatest common divisor (GCD) of two numbers:

int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

int main() {
    int x = 12, y = 18;
    int result = gcd(x, y);  // 调用 gcd() 函数
    cout << "GCD of " << x << " and " << y << " is: " << result << "\n";
    return 0;
}

The above is the detailed content of How to use functions in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn