递增和按位移位运算符优先级?

Increment and bitwise shift operator precedence?

本文关键字:运算符 优先级      更新时间:2023-10-16

增量后缀和前缀的运算符优先级都高于按位左移,但下面打印出不同的结果。

int testValue = 1;
std::cout << ++testValue; //prints 2
//saw it as std::cout << (++testValue);
testValue = 1;
std::cout << testValue++; //prints 1
//thought it was std::cout << (testValue++);

为什么第二个示例中显示的递增后缀在插入之前打印 1?我认为它像增量前缀案例一样更紧密地绑定到testValue,所以我认为它会先递增,然后再用std::cout打印。

<<不是按位运算符,而是insertion operator。 cplusplus参考:

作为类 ostream 的对象,字符可以写入其中 作为使用插入运算符(运算符<<)的格式化数据。

testValue = 1;
std::cout << testValue++; //prints 1

增量表示在读取变量后完成增量。

你误解了testValue++的作用。

它递增testValue但其评估是在递增之前进行的。

该行

std::cout << testValue++; 

相当于

std::cout << testValue;
testValue = testValue + 1;