Sizeof operator in #define directives

I was looking through the code and I ran into this:

#else //If not in Debug mode

#define LOG_WARNING(str) do { (void)sizeof(str); } while(0)
#define LOG_INFO(str) do { (void)sizeof(str); } while(0)

// ... More #define directives

#endif

      

Apparently do { (void)sizeof(str); } while(0)

carefully written, so the directive can be completely ignored by the compiler.

How it works?

+3


source to share


1 answer


The operand sizeof

is invaluable, so it ensures there is no work to be done at runtime. The macro simply ignores the constant value; the compiler can see that it has no effect, so it shouldn't generate code from it.

The advantage that it does nothing is that the compiler still checks that the argument is a valid expression; you don't accidentally damage the debug build when you change your code and only compile for release.

The advantage over the (void)str

one mentioned in the comments is that it would evaluate the expression, and the compiler might not be able to fix it, as these could be side effects. For example:



extern std::string get_message(int code);
LOG_INFO(get_message(code));  // -> (void)get_message(code);

      

in a release build, a function is called and ignores the result, affecting performance.

+4


source







All Articles