-2

sorry if my question is duplicate or not worth answering. I have been the following code that produces the result that I am not understanding how.

int x=5;
int y;
y = ++x * ++x;
cout<<x <<endl;
cout<<y;

According to my little understanding of programming, the value of y should be 42, but, the output on the computer is 49. Kindly help what will be the output of variable y. I am executing the code in Dev-C++. Thanks in advance.

Waheed
  • 7
  • 2

1 Answers1

2

The short answer is that you have an undefined behavior in there.

The exact answer depends on which standard you use.

Pre C++11, we had the notion of sequence points. Intuitively, they are points in which all the values have been properly stored, such as at the end of statement (at the semicolon). The standard says that

Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

, which means that between 2 sequence points (for the sake of simplicity, read as between 2 semicolons), the value of a variable cannot be changed more than once. You change the value twice, using the increment operator.

C++11 removed the notion of sequence points with relationships of sequenced before, sequenced after or unsequenced, referring to the order in which the expressions are evaluated.

In arithmetic expressions,

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or [...] the behaviour is undefined.

and there is no sequencing between the operators of an arithmetic expression. Therefore, it is still a case of undefined behavior, just for another reason.

This means in practice that the compiler can choose what to do, and, in your case, it produces the results you observe. You should try to avoid undefined behaviour in your programs as much as possible. Below are some references that expand on the subject:

https://en.cppreference.com/w/cpp/language/eval_order

Undefined behavior and sequence points

Paul92
  • 8,827
  • 1
  • 23
  • 37