Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

__func__ outside function definition

Tags:

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 form static 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 declaration static const char __func__[] = "function-name"; appeared, where function-name is the name of the lexically-enclosing function.

UB? Error? Or something else?

like image 613
FrozenHeart Avatar asked Jan 02 '13 13:01

FrozenHeart


1 Answers

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’’."

like image 118
ouah Avatar answered Jan 08 '23 06:01

ouah