在Linux上使用g ++错误输出,在Windows上正确输出

问题描述 投票:1回答:1

我正在学习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()函数的提示,为什么会发生这种情况?

c++ linux windows g++
1个回答
0
投票

得到评论的帮助后,我了解到问题与代码在不同编译器中的执行方式有关,我设法通过显式调用函数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;
} 
© www.soinside.com 2019 - 2024. All rights reserved.