It is just that flag happens to contain garbage value (it doesn't matter). |
It matters. The garbage can be exactly 999. The chance is tiny, but but it does exist. That, by definition is undefined behaviour.
It does not cost you much to explicitly prevent the uncertainty.
int flag = 0;
My first input to your program is 999. Why is it "red"? The 999 is supposed to stop the loop.
Undefined behaviour and bad logic. You can do better than that.
@OP:
A while loop:
1 2 3
|
while ( condition ) {
body
}
|
will repeatedly execute the body as long as the condition is true. Therefore, something should affect the condition.
1 2 3 4 5
|
int input = 0;
int count = 0;
while ( std::cin >> input && input != 999 && count < 6 ) {
++count;
}
|
Here, if input operation fails, then the loop ends.
If input (that can be different each time) equals 999, the loop ends.
If 6 iterations have already occurred, the loop ends.
In any other case the loop keeps repeating.