与操作员优先级混淆

本文关键字:优先级 操作员 | 更新日期: 2023-09-27 18:15:54

两者之间的区别使用前缀和后缀

的操作符优先级
    // program 01
    int x =10;
    int c = x++ + ++x;
    Console.WriteLine(c); // output will be 22
    // program 02
    int x =10;
    int c = ++x + x++;
    Console.WriteLine(c); // output will be 22
    // program 03
    int x =10;
    int c = ++x + x;
    Console.WriteLine(c); // output will be 22

与操作员优先级混淆

这些表达式是如何求值的:

1:

x++ + ++x;
 |  |  |
 1  3  2
1: increments x to 11, returns value before increment (10)
2: increments x to 12, returns value after increment (12)
3: 10 + 12 = 22

2:

++x + x++;
 |  |  |
 1  3  2
1: increments x to 11, returns value after increment (11)
2: increments x to 12, returns value before increment (11)
3: 11 + 11 = 22
3:

++x + x
 |  | |
 1  3 2
1: increments x to 11, returns value after increment (11)
2: returns value of x (11)
3: 11 + 11 = 22

值得注意的是,某些C/c++实现可能以不同的顺序计算这个表达式。此页有与op相同的未定义行为示例。http://en.cppreference.com/w/cpp/language/eval_order