Home  >  Article  >  Backend Development  >  const qualifier for C++ function pointer parameters

const qualifier for C++ function pointer parameters

WBOY
WBOYOriginal
2024-04-20 18:36:01750browse

C++ 函数指针参数的 const 限定符

C const qualifier for function pointer parameters

A function pointer is a pointer to a function, which provides the ability to dynamically call functions at runtime. Function pointer parameters are often used to pass callbacks to other functions.

const Qualifiers can be applied to function pointer parameters to specify that the function pointed to by the function pointer cannot be modified. This ensures that the function pointed to by the function pointer is not accidentally overwritten or modified during the call.

Syntax

void foo(void (*func)(int));

In the above example, the foo function accepts a function pointer parameter func, which points to a function that accepts a single integer Parameter function. const The function pointed to by the qualifier cannot be modified.

Practical case

Consider a function that calculates the greatest common divisor of two integers:

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

We can pass the gcd function as a function pointer parameter Pass to create a function that returns the least common multiple of two numbers:

int lcm(int a, int b) {
    return a * b / gcd(a, b);
}

In the main function we can use the std::function wrapper class To create a const function pointer pointing to the gcd function:

int main() {
    std::function<int(int, int)> gcd_ptr = std::function<int(int, int)>(gcd);
    int result = lcm(12, 18);
    std::cout << result << std::endl;
    return 0;
}

Output:

36

In this example, gcd_ptr is a const function pointer pointing to a gcd function, because it is created using the std::function wrapper class, which ensures that the pointed function cannot be modified.

The above is the detailed content of const qualifier for C++ function pointer parameters. 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