Gobo
Gobo

Reputation: 23

Comparison warning

I'm doing an exercise to reverse the order of a vector. My program works, but I am getting a warning in the for loop I am executing below:

    void reverse (vector<int>& v){
        for(int i=0; i<v.size()/2; ++i){
            swap(v[i],v[v.size()-1-i]);
        }
    }

on the line of the for loop, I am getting the warning message "comparison between signed and unsigned integer expressions [-Wsign-compare]". I am using Stroustrop's Programming Principles and Practice Using C++, and he uses basically that general format (without the / 2). Should I be writing this for-loop differently?

Upvotes: 2

Views: 61

Answers (2)

cup
cup

Reputation: 8257

The size function in a vector returns a size_t which is basically an unsigned int. When you get a warning like that, check the variable types that you are being warned about. One way of getting rid of the warning is to change the loop variable

for(size_t i=0; i<v.size()/2; ++i)

The problem is that still computes v.size()/2 every time. So a better way would be

for(size_t i=0, stop=v.size()/2; i < stop; ++i)

Upvotes: 1

Adrian Mole
Adrian Mole

Reputation: 51854

The size() function in the std::vector class returns a size_t value, which is always defined as an unsigned type (though its bit-width may vary between platforms). This is generally true of all standard functions that return container, array or string size values (like std::strlen()), and the type is also used as the actual type for array indexes, and parameters to operators such as new int[n].

To avoid the warning, simply declare your loop variable (i) as a size_t rather than a (signed) int:

    void reverse (vector<int>& v){
        for(size_t i=0; i<v.size()/2; ++i){
            swap(v[i],v[v.size()-1-i]);
        }
    }

Upvotes: 0

Related Questions