Quote:Original post by Nairou
That got me wondering, what about things like #ifdef? For example, will the compiler optimize the following two examples into the same thing? If so, I wonder if there are any advantages of one over the other. The second seems more friendly to me, less hackish than the first.
Most popular compilers will elide the unreachable code, making the two implementations act as if they do the same thing.
There are fundamental differences, however, and most of the advantages go to the preprocessor construct in this case.
(1) A preprocessor value can be set extralingually (usually through a command-line option to the compiler, such as -DIS_SERVER=1). Thus, you can autodetect and set various compile-time options, something you can't do using C++ constants.
(2) Code within an #ifdef block is never even seen by the compiler. That means if you have, say, functions calls that do not exist on some platforms then you can still compile your code. For example,
#ifdef _WIN32 int istat = WSAStartup( ... ); #endif
You can't do that at all using C++ constants. You would have to revert to some kind of wacky template specialization.
Quote:Original post by SneftelFor most modern compilers, yes. To make sure of it, though, it's a good idea to force internal linkage of constants used in this way (by declaring the variable as static, or putting it in an anonymous namespace).
Simply putting it in an anonymous namespace forces external linkage. If you want internal linkage you will have to make it static, regardless of the namespace in which you put it (don't forget "global" is just a namespace like any other).
--smw