-2

I have following simple program that initialize values for three variables and then gives output as expression.

#include<iostream>
#include<conio.h>
using namespace std;

int main()
{
   volatile int a = 10, b = 20, c = 30;
    cout << a+b+c << " " << (c=c*2) << " "<< (b =b*2);
    getch();
    return 0;
}

Output I am getting for above code is

 110 60 40

But a=10,b=20 and c=30 so a+b+c should be 10+20+30 = 60

Akash Sharma
  • 771
  • 1
  • 7
  • 17

3 Answers3

0

This is because the arguments to the function are processed from right to left but are printed from left to right.

Akash Sharma
  • 771
  • 1
  • 7
  • 17
0

In C++, the order of evaluation of function arguments is undefined. That is, in the statement

std::cout << a+b+c << " " << (c=c*2) << " "<< (b =b*2);

you get different results depending on which subexpressions are evaluated first. A compiler can choose to evaluate the arguments to the output operators from left to right but it is also free to evaluate them in a different order, e.g., right to left, then do the appropriate functions calls.

Dietmar Kühl
  • 141,209
  • 12
  • 196
  • 356
0

The output from this code is undefined.

In C++, if assigning a variable, you are only allowed to use in the same statement for purposes of calculating the new value. Any other use has undefined effect. (Note, you evaluate c for the purposes of printing (the 1st print clause), and for the purposes of calculating a new c (the c=c*2).

The later use is sanctioned, the former isn't.

Most compilers will calculate the first use of c as either the value before OR the value after the assignment, but in fact they arent even obliged to have it evaluate to anything related. And even if related, may not be a value it ever logically held, eg if the assignment were (c=2*c+5), you could just as easily find this mapped to c*=2, c+=5, and the first print clause might get the intermediate state, rather than the starting or end state.

The same problem exists for b. Compilers cant even be assume to be consistent in their handling of this, since what they do may reasonably depend on register allocation, which depends on local code.

RichardPlunkett
  • 2,958
  • 11
  • 14