C++参考资料之谜:我的输出似乎颠倒了。为什么?

发布于 2024-09-25 01:01:28 字数 259 浏览 1 评论 0原文

以下代码的输出是不带引号的“321”。为什么不是“123”?

#include <iostream>
using namespace std;

int& inc(int& start)
{
 return ++start;
}

int main()
{
 int i = 0; 
 cout << inc(i) << inc(i) << inc(i) << endl;
}

The output of the following code is "321" without quotes. Why not "123"?

#include <iostream>
using namespace std;

int& inc(int& start)
{
 return ++start;
}

int main()
{
 int i = 0; 
 cout << inc(i) << inc(i) << inc(i) << endl;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

幽蝶幻影 2024-10-02 01:01:28

您的代码调用未指定的行为,因为评估的顺序
operator<< 的参数未指定

operator<< 的调用修改同一变量。不要编写这样的代码。

注意:请注意,该代码不会导致未定义的行为,因为在修改 i 和读取它之间存在序列点(至少一个函数调用)。

Your code invokes Unspecified Behaviour because the order of evaluation of the
arguments of operator<< is unspecified

Calls to operator<< modify the same variable. Don't write such code.

Note : Note that the code doesn't result in undefined behavior because there are sequence points (at least one function call) between when i is modified and when it is read'.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文