TheProgramMAN123
TheProgramMAN123

Reputation: 487

Why is this loop running invisible code? and not working in order

int ASCI1 = 1;

for (int i = 1; i < 8; i++)
{
    cout << ASCI1 << endl << ASCI1++;
}

I get output :

2
13
24
35
46
57
68

7 (and no end line here for some reason).

The idea was to get

1
2
3
4 
etc.

Completely stumped, please help!

Upvotes: 1

Views: 125

Answers (4)

Ajay
Ajay

Reputation: 18429

Let's consider the very first iteration of for loop (when ASCI1 is 1):

cout << ASCI1 << endl << ASCI1++;

This statement is transformed as (hypothetically):

cout.print(ASCI1).printNewLine().print(ASCI1++);

As others commented, order of evaluation is not defined. In your case, ++ operation is being performed first, but the last print statement is to be passed old value of variable (i.e. 1), and not incremented value. The just incremented value is passed to first print. Hence it becomes:

   cout.print(2).printNewLine().print(1); 

The value of ASCI1 would be 1 after this statement. It will give output as:

2\n
1

And the next iteration would print 3 and 2 the same way I explained above

2
13
2\n

You've been lucky that you used just one ++ statement in one statement.

What if first print is passed 1 and second is passed 2, or 1 and 1. It is up to compiler, and the compilation phase. This is Undefined Behaviour (UB)

Upvotes: 0

AndyG
AndyG

Reputation: 41110

The << operator is not defined as a sequence point in C++, so it's possible for ASCI1 and ASCI1++ to be evaluated in any order.

If you try to perform reads and writes on an object with unsequenced evaluation, then you have undefined behavior, hence the garbage output you are seeing.

Finally, you don't see a newline at the end 1) because you got lucky, and 2) because even if your loop executed as you had planned, you're still performing a write without following it up with another endl

Upvotes: 6

John M
John M

Reputation: 1479

The code is not invisible. You are outputting two numbers per each loop execution, one on first line, then a newline, then another on the next line.

Just do

int ASCI1 = 1;
for (int i = 1; i <= 4; i++){
    cout << ASCI1++ << endl;
}

Upvotes: 2

Slava
Slava

Reputation: 44268

Not clear why you created that mess, just use:

int ASCI1 = 1;

for (int i = 0; i < 4; i++) {
    cout << ASCI1++ << endl;
}

Note you should either start with 0 (as shown) or change condition to <= otherwise you will loop 3 times instead of 4.

Upvotes: 1

Related Questions