gpt4 book ai didi

c++ - 代码块不正确的 c++ 输出

转载 作者:行者123 更新时间:2023-11-28 05:22:25 25 4
gpt4 key购买 nike

我有以下代码:

#include <iostream>

using namespace std;

Sum (int a, int b)
{
int x = a - b;
//cout << x << " \n";
return x;
}

int main()
{
int s1 = Sum(3, 6);
cout << s1;

return 0;
}

系统信息:Win 7 Sp1 x64 Ultimate/Professional 或 Win 8.1 x64代码块 16.01 MinGW调试器名称和版本:GNU gdb (GDB) 7.6.1编译器:GNU GCC 编译器

这段代码编译没有问题,但这就是问题所在,应该有错误。

1) 函数 Sum,没有返回值,在 http://cpp.sh/ 上因此它不允许我编译。

2) 无论我是否写“return x”,变量的 s1 值都是 -3。

它每次都会以某种方式传递 x 的值,但是如果我取消注释“return x”上方的 cout 语句,一切都会开始解决正如预期的那样,这到底是怎么回事 :) --> s1 将在没有 return 语句的地方有一个随机值(因为它在用于函数调用之前没有初始化)和 -3 当return 在那里。

我已经在 3 台不同的计算机上尝试过,它们都表现出相同的行为。所以我不认为机器是问题所在。我也尝试过使用不同的编译器,但我不知道我是否正确配置了它们并且它们没有正确的调试器?我尝试了 Borland c++Digital MarsBorland 有一个新版本 10.1 而不是 codeblocks 支持的 5.5,我无法使新版本工作。我什至不知道这是编译器问题还是程序问题?

我正在尝试学习 C++,这很烦人。我们的老师在类里面使用的是相同的软件,但在 Linux 上运行,而且运行完美。

题外话:有没有办法在这里插入带有行号的代码?第一次发帖在这里所以我还是新手:)。

谢谢!

最佳答案

转到“项目”->“构建选项”->“编译器设置”选项卡->“编译器标志”

并禁用-fpermissive

-fpermissive Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

或者在代码顶部使用 pragma 禁用它:

#pragma GCC diagnostic ignored "-fpermissive"

您也可以尝试在“编译器标志”选项卡中添加标志“-pedantic”

顺便说一句:

如果你尝试 online :

#pragma GCC diagnostic error "-fpermissive"

using namespace std;

Sum (int a, int b)
{
int x = a - b;
//cout << x << " \n";
return x;
}

int main()
{
int s1 = Sum(3, 6);
cout << s1;

return 0;
}

您的行为与您描述的完全相同!

关于c++ - 代码块不正确的 c++ 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41198688/

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