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

How to use functions in C++?

PHPz
Release: 2024-04-12 13:36:12
Original
1057 people have browsed it

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) {
    // 函数体
}
Copy after login
Copy after login

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);
Copy after login

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

return_type function_name(parameter_list) {
    // 函数体
}
Copy after login
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template