0

I am quite new to c++, and I believe the answer to my problem is very, very simple.

I've been using the Eclipse IDE, but have recently changed to a simple text editor and using the command line for compiling. (As i currently don't have my own computer, and I am not allowed to install anything on the one I am using).

However, while writing a program, I noticed that whenever I had nested loops, it would only run the inner loop.

I've tried compiling my code using different online compilers, which results in the same problem.

Because of this, I believe that the problem is related to something simple, that Eclipse was taking care of automatically.

#include <iostream>

int main() {
  for (int i; i<3; i++) {
    for (int j; j<3; j++) {
      std::cout << j << std::endl;
    }
  }
  return 0;
}

Above is the simplest example, I could think of, that produces the problem. The expected output is 0, 1, 2, 0, 1, 2, 0, 1, 2, however it only outputs 0, 1, 2 when I compile and run it.

1
  • First of all, use for(int i = 0;.. , you are not guaranteed to have zero value there in general. Same with j. Commented Apr 8, 2019 at 23:51

2 Answers 2

5

You're not initializing the i and j variables to 0, so the variables start off by having undefined values. Fix to:

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        std::cout << j << std::endl;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is so obvious, I can't believe I missed it. Guess I was tunnel-visioning on the IDE-change too much :) Thanks!
Worst than undefined values, it is UB to read uninitialized variables.
0

The problem is that you are using uninitialized variables, which leave them with undefined values

for (int i; i < 3; i++) {
         ^

Try with

for (int i = 0; i < 3; i++) {

3 Comments

This is so obvious, I can't believe I missed it. Guess I was tunnel-visioning on the IDE-change too much :) Thanks!
@dandan I am surprised you didn't get a warning from the compilers you tested.
Worst than undefined values, it is UB to read uninitialized variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.