Search code examples
c++for-loopundefined-behaviorunsigned-integermodular-arithmetic

C++ code is giving a run-time error in the condition of for loop Whereas it is compiling correctly if it is replaced by code which makes same sense


#include<bits/stdc++.h>
using namespace std;

int main() {
vector<int> luck;
int k = 10;
int sum = 0;
for(int  i = 0; i<5; i++) luck.push_back(i);

for(int i = 0; i<luck.size() - k; i++) sum+=luck[i]; //RUNTIME ERROR

cout<<endl<<sum;
return 0;
}

wheareas it is giving correct output if I add

int boundary = luck.size() - k;

and replacing the condition of second 'for' loop by

i<boundary;

Here's the complete errorless code, again:

#include<bits/stdc++.h>
using namespace std;
int main() {
vector<int> luck;
int k = 10;
int sum = 0;
for(int  i = 0; i<5; i++) luck.push_back(i);

int boundary = luck.size() - k;   // HERE 
for(int i = 0; i<boundary; i++) sum+=luck[i]; //CONDITION CHANGE

cout<<endl<<sum;
return 0;
}

Solution

  • You are mixing unsigned and signed in your for loop. Another way to make your code work is to change:

    for(int i = 0; i<luck.size() - k; i++) sum+=luck[i]; //RUNTIME ERROR
    

    to:

    for(int i = 0; i < int(luck.size() - k); i++) sum+=luck[i];
    

    Explanation:

    luck.size() returns unsigned integer value (std::vector::size_type). When you subtract k from it it's still treated as unsigned integer. Because in your case k > luck.size(), the result is negative. When you assign negative value to unsigned integer, you will get huge positive number instead, so the loop will not stop correctly.

    In second case, assignment (to signed int) treats rhs expression as signed and code works as expected.