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?

1
  • 1
    You didn't initialize i. Commented Dec 17, 2016 at 6:56

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.