Does this get optimized out?
My assert macro is like this:
#ifdef DEBUG
#define ASSERT(x) ((void)(!(x) && a开发者_StackOverflowssert_handler(#x, __FILE__, __LINE__) && (exit(-1), 1)))
#else
#define ASSERT(x) ((void)sizeof(x))
I thought this was more or less bulletproof but I seem to be using it a lot in the context of asserting the return value of functions which are important for their side effects. If in my release build I end up compiling
ASSERT(fgets(buffer,sizeof(buffer)/sizeof(buffer[0]),file));
which would become
((void)sizeof(fgets(buffer,sizeof(buffer)/sizeof(buffer[0]),file)));
Is there a chance this will get completely optimized out? I am fairly certain that it won't (I'm calling a function, fgets
), but what exactly is the condition that assures it? Are there any operations with side effects which the optimizer might throw out?
It has nothing to do with optimization. When you evaluate a sizeof
expression, the operand never gets evaluated. For example,
char func(void) { exit(1); }
size_t sz = sizeof(func());
// same as
size_t sz = 1;
If you want to retain the side effects without generating compiler warnings, you can cast to void
as Neil G noted in his answer.
The usual meaning of assert is to be optimized out, so it might be better to stick to those semantics and do
#else
#define ASSERT(x)
#endif
If you insist on it not being optimized out, why not just do
#else
#define ASSERT(x) ((void)(x))
#endif
?
精彩评论