I just ran into a piece of code that not only compiles, but gives the expected result (where x is an integer value):
int y = (int)(0.5 * x * x + + + 0.6 * x + 1.2);
It took me a while to figure out what happens and I must say it was an interesting operator problem. Without compiling the program, what are the results of the following operations and why?
int a = 1;
int b = 2;
int z = a + + + b;
int z1 = a + - + b;
int z2 = a + - - b;
int z3 = a - - + b;
int z4 = a - - - b;
int z5 = a +- b;
I still have one question, though: does the standard give such results or is it compiler specific?开发者_运维百科
Explanation: Because the + and - operators have spaces between them, the "+ + +" sequence is not compiled as "++ +", but as unary operators on the right member. So
int y = (int)(0.5 * x * x + + + 0.6 * x + 1.2);
actually gives:
int y = (int)(0.5 * x * x + 0.6 * x + 1.2);
which was the expected result.
So,
z = a + + + b = a + + (+b) = a + (+b) = a + b = 3;
z1 = a + - + b = a + - (+b) = a + (-b) = a - b = -1;
z2 = a + - - b = a + - (-b) = a + (+b) = a + b = 3;
z3 = a - - + b = a - - (+b) = a - (-b) = a + b = 3;
z4 = a - - - b = a - - (-b) = a - (+b) = a - b = -1;
z5 = a +- b = a + (-b) = a - b = -1;
Answering the question as formulated in the title:
So you think you know the priority of operators in c++?
No, I do not think so, and even more, I have no intention to learn it. Whenever unsure when reading, I will check documentation, whenever unsure when writing, I will use parentheses. I need my memory to remember more important things.
[source] Unary +/- bind tighter than addition/subtraction +/-, and associate right. Thus...
int a = 1;
int b = 2;
int z = a + + + b; // equivalent to a + (+(+b))
int z1 = a + - + b; // equivalent to a + (-(+b))
int z2 = a + - - b; // equivalent to a + (-(-b)) = a + b
int z3 = a - - + b; // equivalent to a - (-(+b)) = a + b
int z4 = a - - - b; // equivalent to a - (-(-b)) = a - b
int z5 = a +- b; // equivalent to a + (-b) = a - b
z = 3
z1 = -1
z2 = 3
z4 = 3
z5 = -1
Without compiling, i'd say it's a simple math operator combining
I've learned it with this phrase (translated from Brazilian portuguese):
Different signs = subtract
Equal signs = add
So
int z = a + + + b; // '+' + '+' = '+' , the resulting '+' + '+' = + again.
int z1 = a + - + b; // '+' + '-' = '-' , the resulting '-' + '+' = - again.
int z2 = a + - - b; // '+' + '-' = '-' , the resulting '-' + '-' = +.
int z3 = a - - + b; // '-' + '-' = '+' , the resulting '+' + '+' = + again.
int z4 = a - - - b; // '-' + '-' = '+' , the resulting '+' + '-' = -.
int z5 = a +- b; //simple "different signals = subtract" :)
To sort of answer you question, the answers are not compiler specific. It is neither implementation defined nor undefined behavior.
精彩评论