Fran Cisco
Fran Cisco

Reputation: 1

-Wunused-variable compiler says ERROR

Recently I'm starting to program in C + + (I come from Java, and it costs me a little change haha). Under Windows everything right. The problem is that I switched to Linux and this is where I have problems with the compiler. It is usually when you declare a variable and is not used, the compiler displays a "warning" saying that the variable is not used, but I (under linuxmint 15) throws me as "error" and leaves no compile: C. I do not know if anyone has this happened, but I'm sick at the time of making large programs (more than one class).

a little example: enter image description here

Upvotes: 0

Views: 12536

Answers (1)

kfsone
kfsone

Reputation: 24249

The unusued variable warning is the result of invoking GCC with either

g++ -Wunused-variable ...

If this is the case, don't specify that argument. Or it's because of -Wall:

g++ -Wall ...

In which case, specify -Wno-unused-variable

It's being thrown as an error because you have the '-Werror' argument too.

There are a few reasons for this warning: It is possible to "shadow" variables between scopes in C++ and so a common cause of unused variables is when you have two variables of the same name.

int i = 5;
for (int i = 0; i < 10; ++i) { // << this is SECOND variable called i that hides the previous
}
if (day == "Monday") {
    int i; // << you can't see the second i here, this is a third that also hides the first.
    ...
}
// std::cout << "i = " << i << std::endl; // we can see original i again here

There are two variables called "i" here. If you uncommented the last line, it would print 5, unrelated to the two additional variables called 'i'.

Without the std::cout, though, the original, outer, i is never used. Perhaps that last "int i" is an error.

Another common problem relates to the ability to have global variables in C++

int Whoops; // GLOBAL: NEVER EVER TOUCH THIS.

int func() {
    int whoops; // LOCAL: ALWAYS TOUCH THIS.
    Whoops = 42; // >W<hoops!
}

You would receive a warning that "whoops" was an unused variable to aide in detecting you had modified the wrong variable.

Upvotes: 2

Related Questions