0

Take a look at the following code:

int start = 3;

vector<int> data;
data.push_back(0);
data.push_back(0);

for (int i=start; i<data.size()-start; i++)
    printf("In...\n");

When running the above code, it will run printf("In...\n"); infinitely. Although based on the condition (3<-1) of the for loop, it should never do this. Weird, huh?

To avoid this, you have to compute the long condition equation first, like:

… …

int end = data.size()-start;
for (int i=start; i<end; i++)
    printf("In...\n");

Why this happens?

1 Answers1

6

size() returns an unsigned value (of type size_t) which causes the expression on the right of the comparison to be promoted to unsigned which then makes the comparison unsigned.

So there are no negative numbers where you think there are, just very large positive ones.

As other people have said, most compilers will warn you about this if you turn up the warning level, and c++ is not a language that can safely be used at a low warning level.

Will Dean
  • 39,055
  • 11
  • 90
  • 118
  • I suspect the people who know what 'UB' is don't need help with this stuff.... ;-) – Will Dean Dec 22 '13 at 11:10
  • @datenwolf No. Not for unsigned. It's well-defined. – P.P Dec 22 '13 at 11:11
  • @BlueMoon: Also if I have a negative signed integer that's casted to an unsigned int? – datenwolf Dec 22 '13 at 11:21
  • @datenwolf There's no UB in the comparison part but UB happens when `i` overflows INT_MAX.. size_t is usually unsigned int or unsigned long. The negative number is converted into an unsigned value using reduction modulo rule (\*_MAX + 1 -3) and where `i` (as in `i<...`) is converted to unsigned value and then then comparison happens. – P.P Dec 22 '13 at 13:22