Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "unused variable" warning not reported for all variables? [duplicate]

I have this code:

// initializer lists
#include <iostream>
#include <vector>

int main()
{
    int values[] { 1, 2, 3 };

    std::vector<int> v { 4, 5, 6 };

    std::vector<std::string> cities {
        "London", "New York", "Paris", "Tokio"
    };

    return 0;
}

However the gcc compiler gives me unused variable warning only for values array. Why v and cities is not reported?

like image 490
Jacob Krieg Avatar asked Mar 01 '14 09:03

Jacob Krieg


People also ask

How do I get rid of the unused variable warning?

Solution: If variable <variable_name> or function <function_name> is not used, it can be removed. If it is only used sometimes, you can use __attribute__((unused)) . This attribute suppresses these warnings.

Why is unused variable an error?

Unused variable warnings are emitted during compiletime and should be a hint to you as the developer, that you might have forgotten to actually process a value that you have bound to a name. Thats the main reason for the warning.

What does unused variable mean in C?

No nothing is wrong the compiler just warns you that you declared a variable and you are not using it. It is just a warning not an error. While nothing is wrong, You must avoid declaring variables that you do not need because they just occupy memory and add to the overhead when they are not needed in the first place.


1 Answers

It is not a primitive value, so its constructor and/or destructor might have desired side effects.

Classical example: a Timer object which measures the time between its construction and destruction: https://stackoverflow.com/a/5302868/1938163

like image 100
Marco A. Avatar answered Nov 15 '22 01:11

Marco A.