函数没有正确打印,每个函数的输出首先被打印,返回的值最后被打印

huangapple go评论61阅读模式
英文:

Functions aren't printing properly, couts of each function are printed first and the returned values are printed last

问题

我有这段C++代码,我在CodeBlocks中编写了它:

#include <iostream>
using namespace std;
double square(double arg) {
    cout << "double ";
    return arg * arg;
}
int square(int arg) {
    cout << "int ";
    return arg * arg;
}
int main(void) {
    cout << square(2) << " " << square(2.0) << " " << square('A') << endl;
    return 0;
}

出现这种打印的原因是:
int double int 4 4 4225
而不是:
int 4 double 4 int 4225

我尝试在Visual Studio Code的C++中编译,但仍然得到int double int 4 4 4225。这段代码似乎在在线编译器上打印正常。

英文:

I have this c++ piece of code which I wrote in CodeBlocks:

#include &lt;iostream&gt;
using namespace std;
double square(double arg) {
    cout&lt;&lt;&quot;double &quot;;
   return arg * arg;
}
int square(int arg) {
    cout&lt;&lt;&quot;int &quot;;
   return arg * arg;
}
int main(void) {
   cout &lt;&lt; square(2) &lt;&lt; &quot; &quot; &lt;&lt; square(2.) &lt;&lt; &quot; &quot; &lt;&lt; square(&#39;A&#39;) &lt;&lt; endl;
   return 0;
}

For some reason the print is:
int double int 4 4 4225
instead of:
int 4 double 4 int 4225

I tried compiling in Visual Studio Code's C++, but I still get int double int 4 4 4225. The code seems to print properly on online compilers.

答案1

得分: 3

在C++17之前,operator <<的操作数评估顺序是未排序的。

因此,在以下代码中:

std::cout << " " << square(2.)

square(2.) 可能会在 std::cout << " " 之前被评估(带有其打印副作用)。

自C++17以来,已添加了新的规则,以实现“预期”的行为:

  1. 在位移操作符表达式 E1 << E2 和 E1 >> E2 中,E1 的每个值计算和副作用都会在 E2 的每个值计算和副作用之前排序。
英文:

Prior C++17, evaluation order for operands of operator &lt;&lt; is unsequenced.

so, in

std::cout &lt;&lt; &quot; &quot; &lt;&lt; square(2.)

square(2.) might be evaluated (with its printing side-effect) before std::cout &lt;&lt; &quot; &quot;.

Since C++17, new rules has been added to have "expected" behavior:

> 19) In a shift operator expression E1 << E2 and E1 >> E2, every value computation and side effect of E1 is sequenced before every value computation and side effect of E2.

huangapple
  • 本文由 发表于 2023年7月17日 18:34:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定