Handmade Hero»Forums»Code
Gianluca Alloisio
33 posts
on __func__ or __FUNCTION__
I've tried to find out why
1
__func__
is defined as a variable and not as a literal. I've found out that it is written in the standard of both C and C++.

From the C++ draft n3243, page 197 (the one just before C++11):

The function-local predefined variable __func__ is defined as if a definition of the form
1
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. 102
[ Example:
1
2
3
4
5
6
7
struct S {
S() : s(__func__) { }
const char *s;
};
void f(const char * s = __func__);
// OK
// error: __func__ is undeclared

— end example ]

I too would prefer it to be a literal. :[
Mārtiņš Možeiko
2380 posts / 2 projects
on __func__ or __FUNCTION__
Edited by Mārtiņš Možeiko on
I don't remember where, but I have read that the reason is for __func__ == __func__ expression to be true. Including assigning it to multiple char* variables, and passing down to other functions and only comparing then. If __func__ is an array variable, then it will true. But if it is preprocessor #define, then it's up to compiler optimizer to figure out that it can be same char array (because contents are equal). MSVC, for example, doesn't do this by default. It does only if you specify /GF is enabled (it is part of /O2). See what happens when GF is disabled: https://godbolt.org/g/0W5fof Compiler will compare two different pointers which will evaluate to 0 (false). Remove "-GF-" and compiler will see that pointers are equal at compile time and will evaluate to 1 (true).
Mattie
35 posts
on __func__ or __FUNCTION__
The reasoning I've seen is that it's not a macro because the function name isn't known at pre-processing time, since the code hasn't actually been parsed yet.
Kim
Kim Jørgensen
64 posts
on __func__ or __FUNCTION__
We discussed it a while back in this thread.

/Kim
Gianluca Alloisio
33 posts
on __func__ or __FUNCTION__
Kim
We discussed it a while back in this thread.

/Kim

Uh, I didn't notice it, my bad.

@mmozeiko: I'd prefer to enforce equivalent literal strings to be stores as a single literal. It would get both the goodies and wouldn't be a heavy task (compared to template compilation times ^_^).

@Sizik: yep, it wouldn't be a proper macro but more of a compiler directive. This doesn't mean it's not feasible, in fact Mircosoft does it.