Hey guys !!! need your help with the basic ++ operator problem.
This is with reference to ivor horton's book "Beginning java", where he teaches us about the ++ operator in chapter 2.
we have 3 variables, numapple, numfruit, numorange.
let us say numapple=9 and numorange=7;
numfruit = numapple + numorange;
which yields 16 as answer.
if i write numfruit = numapple + ++numorange;
the answer becomes 17, which is correct.
Now, if i write numfruit = numapple+++numorange why do you think the answer comes out to be 16 again and not 17. what is the logic behind it. i know we can use paranthesis or spaces and stuff, but what do you all think is the logic behind it.
Spaces would be enough in this case. The spaces tell the compiler what +++ means: either + ++ (addition and pre-increment) or ++ + (post-increment and addition). In fact, for readability, I think it's always better to put spaces around any operator.
But you are right: if you ever get an unexpected result for a term, try adding parentheses - most likely you misinterpreted the precedence rules.
The Java compiler isn't that smart sometimes. Consider the following:
For a developer it is quite clear what most mean (a+++b could be considered as a + ++b as the only exception), yet the compiler doesn't understand. That's probably because both ++ and + are operators, and the scanner part is greedy - it will find ++ as one operator, not + and + as two.
So the compiler probably sees these statements as this:
Therefore, like I already said, add spaces around your operators. It will make it easier to read, and easier for the compiler to know what you mean. Also, the chances of any ambiguity for the developer (as in a+++b) will be erased.
seetharaman venkatasamy wrote:Interesting ! Rob Rocks
Joined: Aug 16, 2007
Rob Prime wrote:The Java compiler isn't that smart sometimes.
If you submit this kind of examples to SUN is there any scope of improvement? I think interpreter does this job so there might be some scope of improvement.
Or SUN has provided documentation about this and we are supposed to accept it and live the life?
Technically it should be possible to change the compiler so none of these examples will give a compiler error. However, it most likely requires rewriting of several grammar rules, and as such will take a lot of work, and even more testing (since basically the entire compiler changes).
I doubt Sun will put that much effort into it for something that can easily be prevented by adding a few spaces - something that is a good recommendation anyway, even if it wouldn't be necessary to prevent compiler errors.