Home >Backend Development >C++ >Can I Take the Address of a Standard Library Function in C 20?
While working with C , you may wonder if you can obtain the address of a function residing in the standard library. This question is pertinent, as it can impact the utilization of those functions in various scenarios.
In the following code snippet, two calls to std::invoke are made:
std::invoke(std::boolalpha, std::cout); // #1 std::cout << std::invoke(static_cast<ctype_func>(std::tolower), 'A') << '\n'; // #2
Is the expected output of this code guaranteed in C 20?
No.
The behavior of C programs is explicitly undefined when an attempt is made to form a pointer to a standard library function, unless that function has been explicitly designated as an addressable function. This is stated in [namespace.std] of the C standard.
In the first call to std::invoke, we attempt to obtain a pointer to std::boolalpha. Luckily, [fmtflags.manip] comes to our rescue:
Each function specified in this subclause is a designated addressable function ([namespace.std]).
std::boolalpha is indeed a function specified in this subclause, making this line well-formed and equivalent to:
std::cout.setf(std::ios_base::boolalpha);
Unfortunately, for the second call, [cctype.syn] informs us:
The contents and meaning of the header <cctype> are the same as the C standard library header <ctype.h>.
Nowhere in this standard library header is std::tolower explicitly designated as an addressable function. Hence, the behavior of this C program is undefined, potentially resulting in a compilation error.
The expected output of this code is not guaranteed, and the code may not even compile successfully due to the undefined behavior associated with taking the address of std::tolower.
Additionally, this applies not only to standard library functions but also to member functions declared in the C standard library. Taking the address of such member functions also results in undefined behavior.
The above is the detailed content of Can I Take the Address of a Standard Library Function in C 20?. For more information, please follow other related articles on the PHP Chinese website!