Presuming that your C++ compiler supports them, is there any particular reason not to use
__FUNCTION__ for logging and debugging purposes?
I'm primarily concerned with giving the user misleading data—for example, reporting the incorrect line number or function as a result of optimization—or taking a performance hit as a result.
Basically, can I trust
__FUNCTION__ to always do the right thing?
__FUNCTION__ is non standard,
__func__ exists in C99 / C++11. The others (
__FILE__) are just fine.
It will always report the right file and line (and function if you choose to use
__func__). Optimization is a non-factor since it is a compile time macro expansion; it will never effect performance in any way.
In rare cases, it can be useful to change the line that is given by
__LINE__ to something else. I've seen GNU configure does that for some tests to report appropriate line numbers after it inserted some voodoo between lines that do not appear in original source files. For example:
Will make the following lines start with
__LINE__ 100. You can optionally add a new file-name
#line 100 "file.c"
It's only rarely useful. But if it is needed, there are no alternatives I know of. Actually, instead of the line, a macro can be used too which must result in any of the above two forms. Using the boost preprocessor library, you can increment the current line by 50:
#line BOOST_PP_ADD(__LINE__, 50)
I thought it's useful to mention it since you asked about the usage of
__FILE__. One never gets enough surprises out of C++ :)
Edit: @Jonathan Leffler provides some more good use-cases in the comments:
Messing with #line is very useful for pre-processors that want to keep errors reported in the user's C code in line with the user's source file. Yacc, Lex, and (more at home to me) ESQL/C preprocessors do that.