0

I am not able to understand sequence of evaluation in following program. As per standard, in each statement I have modified value of 'a' only once. Can anybody help me?

int a = 2;
int b = a+++a;
std::cout << b << " ";
a = 2;
b = a + + + a;
std::cout << b << " ";

a = 2;
b = a++ + a;
std::cout << b <<  " ";

a = 2;
b = a + ++a;
std::cout << b << std::endl;

Output: 5 4 5 6

Cool Goose
  • 870
  • 10
  • 16
  • The rule is not just that a scalar object may not be modified more than once but also that you may not both modify a scalar object and separate use its value. Specifically, C 2018 6.5 2 says “If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object **or a value computation using the value of the same scalar object**, the behavior is undefined.” All your assignments to `b` both modify `a` and use it separately except in `a + + + a`, which is `a + (+ (+ a))`, which equals `a + a`. – Eric Postpischil Mar 14 '22 at 12:43
  • For example, in `a + ++a`, the `++a` modifies `a`, and the first `a` uses the value without any sequencing relative to the modification. – Eric Postpischil Mar 14 '22 at 12:44

0 Answers0