Nick Nick - 1 year ago 78
C Question

Why gcc and clang both don't emit any warning?

Suppose we have code like this:

int check(){
int x = 5;

++x; /* line 1.*/

return 0;
}

int main(){
return check();
}


If
line 1
is commented out and the compiler is started with all warnings enabled, it emits:

warning: unused variable ‘x’ [-Wunused-variable]


However if we un-comment
line 1
, i.e. increase x, then no warning is emitted.

Why is that? Increasing the variable is not really using it.

This happen in both GCC and Clang for both and .

Answer Source

Yes.

x++ is the same as x = x+1;, the assignment. When you are assigning to something, you possibly can not skip using it. The result is not discarded.

Also, from the online gcc manual, regarding -Wunused-variable option

Warn whenever a local or static variable is unused aside from its declaration.

So, when you comment the x++;, it satisfies the condition to generate and emit the warning message. When you uncomment, the usage is visible to the compiler (the "usefulness" of this particular "usage" is questionable, but, it's an usage, nonetheless) and no warning.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download