Cisplatin Cisplatin - 1 month ago 6
C++ Question

C++ program hangs due to a `uint32_t` for-loop

I have the following program (this is it in its entirety, except comments):

#include <iostream>
#include <vector>

void sieve(uint32_t n) {
for(uint32_t i = 0; i < n; i++) {
for(uint32_t j = i * i; j < n; j += i) {
}
}
}

int main(int argv, char * argc[]) {
sieve(10);
return 0;
}


It compiles just fine. When I run it, it just hangs forever. Even if I put
std::cout << "Test"
as the first line in
main
, it never prints.

Am I missing something obvious here?

Answer

for(uint32_t j = i * i; j < n; j += i) {

First time through i is 0 and so j doesn't actually change (j += 0) ==> infinite loop

Comments