1
int i=1;
int n = (++i)+(++i);

In C++ the above code has undefined behavior. I want to know in Java, does it have defined behavior and give the expected answer n=5 in this case. In Java, the order of evaluation between two sides of + is defined. The key point is whether Java would always produce a temporary value 2 for the first ++i.

Yang Zhao
  • 315
  • 1
  • 5
  • 3
    **Yes**. It is defined behavior in Java. Basically unreadable though. – Elliott Frisch Apr 16 '23 at 16:44
  • 3
    The sections of the JLS that define the behavior are: 15.7. "Evaluation Order", 15.15.1. "Prefix Increment Operator ++", and 15.18.2. "Additive Operators (+ and -) for Numeric Types". – Stephen C Apr 16 '23 at 16:49

0 Answers0