__func__
: The 'magic' constant
Tags: /
c
/
__func__
is an implicitly declared ‘magic constant' which will ‘hold the name of the current function as a string'. ¹
It is mentioned in C99 under 6.4.2.2 Predefined identifiers
(draft version):
The identifier
__func__
shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declarationstatic const char __func__[] = "function_name";
appeared, where
function_name
is the name of the lexically-enclosing function.
__func__
will have the unadorned name of the function. No return type, argument types or arguments themselves.
#include<stdio.h>
int main()
{"\nName of function: %s", __func__);
printf( }
The above program will print:
Name of function: main
__func__
is not a macro as the function names will be known only after parsing. Hence __func__
does not catenate with strings. Meaning things like
char here[] = "Function " __func__ " is used";
will give an error.
As mentioned in this stackoverflow post:
Expanding
__func__
at preprocessing time requires the preprocessor to know which function it's processing. The preprocessor generally doesn't know that, because parsing happens after the preprocessing
GCC has another constant __FUNCTION__
which is basically like an alias of __func__
.
Provided for backward compatibility with old version of GCC. ¹
Fun fact: GCC provides yet another 'magic constant' __PRETTY_FUNCTION__
as an extension which is similar to __func__
for C programs but gives the function signature as well in C++.