Skip to content

C++ for loop initializing counter wrong

An answer to this question on Stack Overflow.

Question

I have a simple for-loop in C++ and the initialization statement is:

for (int n = 0; n < this->fileLines.size(); n++) {

For some crazy reason, the value of n is being set not to 0 but to 249758, which causes the for-loop to evaluate wrong.

Any ideas why this is initializing wrong (i.e., not to 0)?

enter image description here

Answer

Have you tried sticking

std::cerr<<n<<std::endl;

inside of the for loop? This seems a more direct way of observing the value during the running of the program to verify whether or not it is doing what you think, and optimization will not give you problems with this output.

Perhaps your program is multithreaded and someone is inappropriately writing to that memory location?