10

I am new to Java and have background of C.I am going through Khalid Moughal's book. On page 126 he gives an example as

   int i = 10;

   int k = ++i + --i; // ((++i) + (--i)).

This clearly violates the sequence point concept as of C,which says that you can't change the value of a variable more than once with in same sequence point. My question is does the same sequence point rule applies in java or not? It may be that he has taken this example just to explain the concept of prefix unary operator and it's side effect but such an example which clearly violates a very fundamental rule of the language is not expected in a book as renowned as Khalid Moughal.

So please confirm it.

Hope you people take it into proper spirit.

Thanks,

Mawia

Rekin
  • 9,731
  • 2
  • 24
  • 38
mawia
  • 9,169
  • 14
  • 48
  • 57
  • 2
    C has a lot of baggage from the fact that there were dozens of compilers and millions of existing programs before the standard was written, so they had to make the standard in such a way that wouldn't break programs that depended on the way a particular compiler optimized things. Also, optimization was pretty primitive, which explains the `register` keyword which allows the programmer to perform micro-optimizations that any decent compiler can do better. – Paul Tomblin Sep 15 '10 at 18:33

2 Answers2

9

My question is does the same sequence point rule applies in java or not?

No, there are no sequence-points in Java. Order of evaluation (etc) is well defined in Java.

Also read this answer.

Community
  • 1
  • 1
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • 8
    Even though the order is well defined it should be noted anybody teaching to write code like this should have his license revoked on spot... – EFraim Sep 15 '10 at 18:36
  • I'm here because of a more practical example. I wanted to know if it is safe to do the following in Java... `dest[i] = source[i++];` and I think the answer is yes. – John Henckel Dec 30 '20 at 21:37
0

No, there are no concept of sequence-points in java and the order of is fully defined. Generally speaking, expressions are evaluated from left to right.For formal definition, you can read JLS, section 15.7 about the evaluation order. See this link.

York
  • 503
  • 3
  • 23