英文:
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 <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.) << " " << square('A') << 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以来,已添加了新的规则,以实现“预期”的行为:
- 在位移操作符表达式 E1 << E2 和 E1 >> E2 中,E1 的每个值计算和副作用都会在 E2 的每个值计算和副作用之前排序。
英文:
Prior C++17, evaluation order for operands of operator <<
is unsequenced.
so, in
std::cout << " " << square(2.)
square(2.)
might be evaluated (with its printing side-effect) before std::cout << " "
.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论