在C ++中使用cout递增和递减 [英] increment and decrement with cout in C++

查看:121
本文介绍了在C ++中使用cout递增和递减的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,研究增量和减量运算符。
因此,我尝试了以下示例:

I'm new to C++ and study the increment and decrement operators. So I tried this example:

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

它将在C ++ .NET和QtCreator上返回此 weird 输出,并在线返回5 C ++编译器:

It returns this weird output on C++ .NET and QtCreator and 5 online C++ compilers:

7    5    4

7

奇怪的是,我期望这样的事情:

The weird thing is that I expect something like this:

5    5    6

7

您能解释发生什么情况吗?

Can you explain what happens?

推荐答案

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

Please notice that cout << x++ << ++x; is just another notation for:

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

订单,其中 x ++ 和对 ++ x 语句的评估是 undefined ,因此代码的效果也是如此。

The order in which your x++ and ++x statements are evaluated is undefined, so is the effect of your code.

即使看起来要在您的特定示例中从右到左发生,您应该以任何方式依赖它。

Even if it seems to happens from right to left in your particular examples, you should not rely on that by any means.

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

Just make another experiment by using multiple statements as:

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

您的问题的解决方案是:

The solution to your problem is:

从不编写代码,这会导致未定义的行为! :)

Never write code which results in undefined behaviour! :)

这篇关于在C ++中使用cout递增和递减的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆