用语法糖强制算术优先级

时间:2016-01-08 18:05:30

标签: c# operator-precedence post-increment pre-increment

每天早上起床时,我都会抓起我的咖啡,然后去看看John Skeet前一天的回答。这是我的每日提醒,我不知道多少。今天,对于question,我们讨论了增量运算符,例如++--MSDN doc表示++--的优先级高于*。请考虑以下代码:

         int c = 10;
         c = c++ * --c;

和此代码

        int c = 10;
        c = (c++) * (--c);

在两种情况下c都是100.你会如何强制优先(如果可能的话),这样括号中的值将在乘法之前首先计算?

2 个答案:

答案 0 :(得分:3)

变量之后的++将仅在当前指令之后应用,因为它是后增量。 在变量之前使用++或 - 来实现你想要的东西

int c = 10;
c = ++c * --c ;
Console.WriteLine ( c ) ;

此代码将输出110,因为10 + 1 = 11和11 - 1 = 10所以10 * 11 = 110

答案 1 :(得分:2)

计算机处理一堆操作。

以下......

input_variable="test" &&
ssh root@192.168.7.2 "cd /path/to/file && sed -i \"s/this is not/this is a ${input_variable}/g\" text.txt"

编译成这些操作......

int c = 10;
c = c++ * --c;

...我不确定是什么清除了......但是当你在所有地方使用相同的变量(stloc.0 / ldloc.0)时,你可以看到实际操作在堆栈上工作。 (我在括号{}中有什么)。操作(dup,add,sub和mul)不关心堆栈的变量索引。

嘻嘻哈哈......

//OpCode      // Function                                             Stack      Var c
ldc.i4.s   10 // 10 is pushed onto the stack                          {10}
stloc.0       // pop the stack and store the value in location 0      {}         10
ldloc.0       // location 0 is pushed onto the stack                  {10}       10
dup           // stack value is copied and pushed on stack            {10,10}    10
ldc.i4.1      // 1 is added to the stack                              {10,10,1}  10
add           // top 2 values are popped and the sum is pushed        {10, 11}   10
stloc.0       // pop the stack and store the value in location 0      {10}       11
ldloc.0       // location 0 is pushed onto the stack                  {10}       11
ldc.i4.1      // 1 is added to the stack                              {10,11,1}  11
sub           // top 2 values are popped and the difference is pushed {10, 10}   11
dup           // stack value is copied and pushed on stack            {10,10,10} 11
stloc.0       // pop the stack and store the value in location 0      {10,10}    10
mul           // top 2 values are popped and the product is pushed    {100}      10
stloc.0       // pop the stack and store the value in location 0      {}         100
ldloc.0       // location 0 is pushed onto the stack                  {100}      100     

...汇编成这个......

int c = 10;
c = ++c * c--;