在 C++ 中使用 cout 递增和递减

increment and decrement with cout in C++

我是 C++ 新手,正在研究递增和递减运算符。 所以我尝试了这个例子:

    int x = 4;    
    cout << ++x << "    " << x++ << "    " << x++ << endl << endl;
    cout << x << endl;

它 returns 这个 奇怪的 在 C++ .NET 和 QtCreator 和 5 个在线 C++ 编译器上的输出:

7    5    4

7

奇怪的事情是我期待这样的事情:

5    5    6

7

你能解释一下发生了什么吗?

请注意 cout << x++ << ++x; 只是另一种表示法:

operator<<( operator<< (cout, x++), ++x);

你的 x++++x 语句被评估的 order未定义,你的代码效果也是如此

即使在您的特定示例中它似乎是从右到左发生的,您也不应该依赖它。

只需使用多个语句进行另一个实验:

cout << ++x << " ";
cout << x++ << " ";
cout << x++ << endl;

您的问题的解决方案是:

从不 编写 code 会导致 undefined 行为! :)

您的示例的结果未定义。这是因为一行中 x++++x 的求值顺序未定义。

简而言之,如果您希望在使用时出现可预测的行为 operator ++ 那么它所应用的变量应该只出现一次 在正在计算的表达式中。

这就是所谓的未定义蜂箱,取决于您使用的编译器,为了更好地理解这一点,您必须了解计算机体系结构以及编译器的工作原理:

cout << x++ << hello << x++ << endl

一个编译器可以将此序列转换为二进制序列,这将执行以下操作

increment x 
print x
print hello
increment x
print x
print endl

而第二个编译器可以按如下方式进行

print x
increment x
print hello
print x
increment x
print endl

第三个可以这样操作

print x
print hello
print x
print endl
increment x

往复可以做以下

increment x
print x
print hello
print x
print endl

解决此问题的最佳方法是:

x++;
cout << x << hello;
x++;
cout << x << endl;