若定义: int x,y,z;执行"x=y=3;z=-x+ + +y;"后x,y的值为——
为什么x,y的值分别,为4,3而不是3,4
这个语句有点问题吧。没有说清楚++到底是x的后置++还是y的前置++。这种情况要写括号的!
如果答案是4,3,那就是下面这种情况
z=-x+y;
x++;
结果是x++后变成4,y不变
z=-x+ + +y
等价于
z=-x+y
x++
不可能是3 4
是3 3
相当于
-x+(+(+y))
事实胜于雄辩
这属于坑爹题,不同编译器下解释的都不一样
我用c#语法来写,凡是加号之间带空格,就全被当做普通的加号来处理了,最终z=0
估计原题+之间没有空格,如果有空格,那就是普通加号。下面按没有空格分析。
编译器在Phase 3翻译阶段,按照maximal munch规则,会将z=-x+++y;
转化为下面的tokens: z
, =
, -
, x
, ++
, +
, y
, ;
,即+++
会按++ +
匹配而不是按+ ++
匹配。然后按照运算符优先级,可以得到z = (-x++) + y;
,所以z =-3+3=0, x=4, y=3
FROM https://en.cppreference.com/w/cpp/language/translation_phases#Phase_3
If the input has been parsed into preprocessing tokens up to a given character, the next preprocessing token is generally taken to be the longest sequence of characters that could constitute a preprocessing token, even if that would cause subsequent analysis to fail. This is commonly known as maximal munch.