Search code examples
c++loopsvariablesincrement

Why is 16 printed instead of 17 and the variable not incremented?


#include<iostream.h>
void main()
{
    int A=5,B=10;
    for(int I=1;I<=2;I++)
    {
        cout<<"Line1="<<A++<<"&"<<B-2<<endl;
        cout<<"Line2="<<++B<<"&"<<A+B<<endl;
    }
}

The output of this program is

Line1=5&8
Line2=11&16
Line1=6&9
Line2=12&18

I thought that it will produce 17 and 19 in place of the 16 and 18 in the second and fourth lines of the output. This is because, in the first run of the loop, first the value of A is 5 and the first command prints 5&8 and should increment the value of A by 1, making it 6. In the second command it should print 11&(6+11) which should print 11&17 but the output is not that.

Where is the loophole in my reasoning??


Solution

  • Im not an expert on the subject, but I believe it is because of the order of operations that are performed in the background.

    Mainly "<<" is something called an overloaded operator, which basicly means that someone, somewhere wrote what it should do, and how to do it. And if you have a bunch of things written one after the other, like you have:

    cout<<"Line2="<<++B<<"&"<<A+B<<endl;
    

    The compiler has to do some fancy tricks to make it work. The way the program runs through such code, is from right to left. So in essence it kinda runs in reverse to the way you would think it does. First it pushes endl, then it does A+B and pushes it, then it pushes &, then it increments B and it also pushes it, finaly it pushes Line2= forming the complete "sentence". These are then taken to the console (or whatever else you might have) to be printed to your screen at once.

    As a solution to the issue, try separating cout into 2 lines; something like this:

    cout <<"Line2="<<++B<<"&";
    cout <<A+B<<endl;
    

    Or ,if allowed to, try swaping ++B and A+B, this should also solve the issue, however your results will also be reversed.

    cout<<"Line2="<<A+B<<"&"<<++B<<endl;
    

    tl;dr: A+B happendes before B++, doing them in spearate lines or swaping the positions should solve the problem