Varun Rao Varun Rao - 2 months ago 6
Python Question

Python - How does the following expression get evaluated?

a=5;b=10;a----------------++++++++++++++++++b
# Output: 15


The above is the output of a python script.
Could you please explain how it works? I was quite surprised that it works and gives an answer!!

However a similar such expression doesn't work in Java,C,C++
For instance:

a=10;
b=5;
System.out.println(a---b);//error!!
cout<<a---b;//error
printf("%d\n",a---b);//error


Does this have something to do with the compiler - lexical analyser/syntactical analyser?
I understand there is a "leftmost, eager and greedy" approach taken by compilers, but I dont exactly understand how that works in this case.

Answer

In Python, that's

a - ---------------++++++++++++++++++b

that is, subtracting ---------------++++++++++++++++++b from a.

The prefix -, negation, changes the sign of a number, the prefix + does nothing.
Example:

>>> -+2
-2
>>> +-2
-2
>>> --2
2

Since there are 15 negations, a - ---------------++++++++++++++++++b is equivalent to a - -b, which is a + b.

Java, C, and C++ have prefix and postfix -- and ++ (decrement and increment) operators, and by the "maximal munch rule", your expression would read as

(((((((((((((((((a--)--)--)--)--)--)--)--)++)++)++)++)++)++)++)++)++) b

which, even if those operations on a were legal, would be as much nonsense as a b is.
(Note that a---b is valid; it means a-- - b.)

Details about the workings of the increment and decrement operators can be found in any suitable book.