C ++ review basic knowledge of functions

C ++ review basic knowledge of functions

  To use C ++ functions, you must complete the following tasks:

  1. Provide function definition;

  2. Provide function prototype;

  3. Call the function.

  example:

#include <iostream>
using namespace std;
void simple(); // function prototype
int main() {
    cout << "main() will call the simple() function.\n";
    simple();
    cout << "main() is finished with the simple() function.\n";
    return 0;
}
void simple() {
    cout << "I'm but a simple function.\n";
}

  Here is the output of the program:

 

   When the function simple () is executed, the code in main () is suspended.

1 Define the function

  Functions can be divided into two categories, with return values ​​and without return values. Functions with no return value are called void functions. The general format is as follows:

void function(parameterList) {
    statement(s)
    return;    // 可选
}

  Among them, parameterList (parameter list) specifies the type and number of parameters passed to the function.

  example:

void cheers(int n) {    // 无返回值
    for (int i = 0; i < n; i++)
        std::cout << "Cheers!\n";
}

  Print Cheers! A specified number of times (n). The parameter list int n means that when calling the function cheers (), an int value should be passed to it as a parameter.

  A function with a return value will generate a value and return it to the calling function. The type of this function will be declared as the type of the return value, the format is as follows:

typeName functionName (parameterList) { 
    statements 
    return value;     // return value 
}

  For functions that use return values, you must use return statements. The result must be typeName or can be converted to typeName.

  The function ends after executing the return statement. If there are multiple return statements, the function ends after executing the first return statement encountered. E.g:

int bigger(int a, int b) {
    if (a > b)
        return a;
    else
        return b;
}

  You can write expressions after return, such as:

double cube(double x) {
    return x * x * x;
}

  This function calculates the cubic power, for example, the function call cube (1,2) will return 1.728.

Guess you like

Origin www.cnblogs.com/dirror/p/12742247.html