hafiz031
hafiz031

Reputation: 2710

"cout" chaining while performing increment and decrement produces unexpected result

The following program includes simply increment and decrement operations. As my prediction the program should print "0 1 1 1" but it is printing "1 0 2 0" instead,but why?

#include<iostream>
using namespace std;
int main(void)
{
    int i=0;
    cout<<i++<<" "<<i++<<" "<<--i<<" "<<i++;//this will print "1 0 2 0"
}

...but it works fine if I don't chain the output command like,

cout<<i++<<endl;
cout<<i++<<endl;
cout<<--i<<endl;
cout<<i++<<endl;

Even if they should work in the same way but they are producing different results. But why?

Upvotes: 0

Views: 97

Answers (1)

Chris Hutchison
Chris Hutchison

Reputation: 611

Post and pre-increment when you use i++ it runs after the line when you run ++i it adds before the line is executed so when you did --i it subtracted from i before the line ran for the i++ calls.

try making them all either i++ and i-- or --i and ++i so the results don't vary based on if they're on the same line to not.

Upvotes: 1

Related Questions