gpt4 book ai didi

c++ - 在 Linux 上使用 g++ 输出错误,在 Windows 上更正

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:08 24 4
gpt4 key购买 nike

我正在学习 C++,并决定编写一个小程序来练习变量作用域。问题是我在编译和执行后在 Linux 上得到了不同的(我认为是错误的)输出,而在 Windows 上一切都是正确的。这是代码:

/*main.cpp*/
#include <iostream>
using namespace std;

extern int x;
int f();

int main() {
cout << " x = " << x << endl;
cout << "1st output of f() " << f() << endl;
cout << "2nd output of f() " << f() << endl;

return 0;
}



/*f.cpp*/
#include<iostream>
using namespace std;

int x = 10000;
int f() {
static int x = ::x;
{
static int x = 8;
cout << x++ << endl;
}
cout << x++ << endl; return x;
}

我在 linux 上输入的命令是 $g++ main.cpp f.cpp && ./a.out

期望的输出(windows 输出):

x = 10000
8
10000
1st output of f() 10001
9
10001
2nd output of f() 10002

给定(Linux)输出:

x = 10000
1st output of f() 8
10000
10001
2nd output of f() 9
10001
10002

据我所知,Linux 程序似乎跳过了 int f() 函数的 cout,知道为什么会发生这种情况吗?

最佳答案

在评论的帮助下,我了解到问题与代码在不同编译器中的执行方式有关,我设法通过显式调用函数 f() 解决了“错误”,首先执行它的命令,然后得到返回值。我尽可能地解释了它,所以这里是代码:

int main() { 
cout << " x = " << x << endl;
int temp=f();
cout << "1st output of f() " << temp << endl;
temp=f();
cout << "2nd output of f() " << temp << endl;

return 0;
}

关于c++ - 在 Linux 上使用 g++ 输出错误,在 Windows 上更正,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com