Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (void)0 stop "statement has no effect" warnings?

Tags:

c

macros

I have a trace() macro I turn on and off with another macro, e.g.

#ifdef TRACE
    #define trace(x) trace_val(x, 0)
#else
    #define trace(x) 0
#endif

This generates warning: statement with no effect from gcc when I call trace() with TRACE undefined. After a little searching I found that changing

#define trace(x) 0

to

#define trace(x) (void)0

silences the error. My question is: Why? What's the difference?

like image 379
blueshift Avatar asked Apr 05 '12 03:04

blueshift


2 Answers

The cast to void makes it clear that the programmer intends to throw the result away. The purpose of the warning is to indicate at that it's not obvious that the statement has no effect and thus it's useful to alert the programmer to that in case it was unintentional. A warning here would serve no purpose.

like image 73
David Schwartz Avatar answered Oct 05 '22 04:10

David Schwartz


The warning and the workaround are compiler-specific. What you can do however is the following:

#define NOP do { } while(0)

#ifdef ENABLE_TRACE
    #define TRACE(x) trace_val(x, 0)
#else
    #define TRACE(x) NOP
#endif

This avoids the underlying problem in the first place.

like image 39
Niklas B. Avatar answered Oct 05 '22 02:10

Niklas B.