Search code examples
c++compiler-warningsunsignedsigned

Compiler warnings


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.


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.