What should happened if we use predefined variable __func__
outside a function in C (C99 / C11) and C++?
#include <stdio.h> const char* str = __func__; int main(void) { printf("%s", str); return 0; }
gcc 4.7.2 only give a warning (with -Wall -W -pedantic
enabled) and prints nothing.
Standard doesn't say anything about it explicitly:
ISO/IEC 14882:2011
8.4.1 In general [dcl.fct.def.general]
8 The function-local predefined variable
__func__
is defined as if a definition of the formstatic const char __func__[] = "function-name";
had been provided, where function-name is an implementation-defined string. It is unspecified whether such a variable has an address distinct from that of any other object in the program.
ISO/IEC 9899:2011
6.4.2.2 Predefined identifiers
1 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.
UB? Error? Or something else?
Standard doesn't say anything about it explicitly
This means undefined behavior.
From the C Standard (emphasis mine):
(C99, 4.p2) "If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe ‘‘behavior that is undefined’’."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With