0

I have failed many times when executing a code, I thought it was in my logic in how I use loop statements, but when I tried this code:

int main(){
    cout << "yo \n";
    for(int i; i < 5; i++){
        cout << "meh \n";
    }
}

I was expecting the output:

    yo
    meh
    meh
    meh
    meh
    meh

But in my disappointment, it only showed

    yo

So, what's the problem with this simple block of code?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
kyoto zen
  • 25
  • 1

3 Answers3

3

Because i is uninitialized. Initialize the i value, Like

for(int i = 0; i < 5; i++)

uninitialized variables to hold garbage data.So, this is undefined behaviour.

msc
  • 33,420
  • 29
  • 119
  • 214
1

It is failing many times because it is undefined behaviour to use uninitialized variable i. Any thing can happen in that case.

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
0

Initialise the value of i.i++ is trying to increment an uninitialised variable.