Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence or Maximal Munch Rule comes first for Unary Operators

Here I am having the following piece of code:

int a,b,x;
a=b=1;
x=a+++b;

Now the value of x will be 2 as a is first being post incremented and then it is being added to b.

Following is the compiled byte code :

 0  iconst_1
 1  dup
 2  istore_2 [b]
 3  istore_1 [a]
 4  iload_1 [a]
 5  iinc 1 1 [a]
 8  iload_2 [b]
 9  iadd
10  istore_3 [x]

So the expression will be equivalent to x = (a++) + b.

Now the other expression x=a++++b, won't compile because of the maximal munch rule. It will become x = (a++) ++ b and hence compilation error.

Is the above behavior of x=a+++b because of the precedence of the operator ++ or because of maximal munch rule?

like image 796
Zeeshan Avatar asked Feb 13 '23 16:02

Zeeshan


1 Answers

Quoting from Lexical Translations:

The longest possible translation is used at each step, even if the result does not ultimately make a correct program while another lexical translation would.

Thus, the input characters a--b are tokenized (§3.5) as a, --, b, which is not part of any grammatically correct program, even though the tokenization a, -, -, b could be part of a grammatically correct program.

This would explain why

x=a+++b

is parsed as

x=(a++)+b

On the other hand, a++++b is tokenized as a++, ++, b which causes an error.

like image 137
devnull Avatar answered Apr 29 '23 07:04

devnull