Question

Suppose I have this (C++ or maybe C) code:

vector<int> my_vector;
for (int i = 0; i < my_vector.size(); i++) {
    my_vector[i] = 0;
}

I don't care if it's done right. The important part is in the for-loop declaration. The compiler gives a signed/unsigned mismatch for this, since size() returns an unsigned int, not a signed one. How important is it to change i to unsigned? I declare loop counters as ints out of habit, but if this is a potential error I'll force myself to get out of the habit.

Was it helpful?

Solution

I would say it's very important - you should be compiling with warnings as errors, and strive to fix all warnings. If you leave problems like this in your code, it is easy to get into a habit of ignoring warnings, or letting false positives like this drown out warnings that indicate real problems.

In this case, for this specific error, it's probably not a big deal - on a 32-bit platform you'd have to have more than 2 billion entries in the vector before the unsigned would wrap into a negative signed value. To get a vector like this would exhaust all of your memory, so it's probably not possible to get into a state where signed/unsigned mismatch would matter.

OTHER TIPS

Technically, i should be a vector<int>::size_type. You should get in the habit of using typedefs in your code:

typedef vector<int> VectorType;
VectorType my_vector;
for (VectorType::size_type i = 0; i < my_vector.size(); i++) {
    my_vector[i] = 0;
}

Now, if we change it to a deque, we only change one line. Even if it's some custom container that has a wacky size_type, you get the warm, fuzzy feeling that everything will be ok. And that's worth a lot. Even with just unsigned/signed, there are some tricky promotion issues with using signed/unsigned conversion that will inevitably come back to bite you.

This may be important in the unlikely event that the size of the vector exceeds INT_MAX. If the size of the vector is greater than the maximum value that can be represented in a signed int, then your loop will never terminate.

Well, its important because signed integers have sign, so i could go all the way up becoming a negative value, then no matter how big it is, it would still be less than size(), which doesnt have any sign.

11111111 < 10000000

On most cases of your example, it won't matter. but when your program doesn't work, the first thing you do (or should) is to make sure there are no warnings, so it's a chance not worth taking.

make sure there are as few warnings as possible.

As said above, use vector::size_type; or use an iterator to loop through your vector. Make sure to handle all of your own warnings as errors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top