0

So I have two C++ codes:

The first one:

int main()
{
    int a=10, b=8;

    b=a;
    ++a;
    b++;

    cout<<a<<"\n"<<b<<"\n"<<--b<<"\n";

    return 0;
}

The second one:

int main()
{
    int a=10, b=8;

    b=a;
    ++a;
    b++;

    cout<<a<<"\n";
    cout<<b<<"\n";
    cout<<--b<<"\n";

    return 0;
}

Their respective outputs are:

The first output:

11
10
10

The second output:

11
11
10

As you can notice, if I cout the values using a single line, the output is different than the output if I cout the values using multiple lines.

Can anybody please explain what's happening?

Thanks.

sequel
  • 196
  • 2
  • 15

1 Answers1

-2

When you are executing in one line then

--b;

value is evaluated first and then printed in both (b and --b) .

and when you are executing cout in new line then :

--b; 

value is evaluated at last.

  • The issue with evaluating the same value multiple times in one expression is described in the "possible duplicates" my friends above have already posted. Please do give them a read. – Gem Taylor Aug 28 '18 at 10:54