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
  • 60,915
  • 9
  • 122
  • 205
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
  • 32,079
  • 22
  • 110
  • 197
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
  • 11,445
  • 5
  • 53
  • 73
0

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