Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 c and c++.

like image 257
Nick Avatar asked Jul 27 '17 09:07

Nick


2 Answers

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.

like image 152
Sourav Ghosh Avatar answered Sep 21 '22 03:09

Sourav Ghosh


With the preincrement you are incrementing and assigning the value to the variable again. It is like:

x=x+1

As the gcc documentation says:

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

If you comment that line you are not using the variable aside of the line in which you declare it

like image 35
Jesferman Avatar answered Sep 22 '22 03:09

Jesferman