简体   繁体   English

MinGW GCC编译错误的代码,没有警告或错误

[英]MinGW GCC compiles a faulty code without warning or error

Can you explain to me why doesn't MingW GCC produce warning in this code: 你能解释一下为什么MingW GCC在这段代码中没有产生警告:

int main()
{
    int num;
    int people[ num ];
    cout << people[ 0 ];
    cin >> num;
}

But here, I only replaced the last statement with num = 1 and now there is a warning... 但是在这里,我只用num = 1替换了最后一个语句,现在有一个警告......

int main()
{
    int num;
    int people[ num ];  //warning: 'num is used uninitialized..'
    cout << people[ 0 ];
    num = 1;
}

I think because you are only using the first element, it optimizes out the num in the first example. 我认为因为你只使用第一个元素,所以它在第一个例子中优化了num。 It just creates a single element array. 它只是创建一个单元素数组。 In the second case since you actually use the num, it gives the error 在第二种情况下,因为您实际使用num,它会给出错误

This code: 这段代码:

#include <iostream>
using namespace std;

int main()
{
    int num;
    int people[ num ];
    cout << people[ 0 ];
    cin >> num;
}

will only produce an error (in fact a warning) in g++ if the -pedantic flag is used. 如果使用-pedantic标志,则-pedantic在g ++中产生错误(实际上是警告)。 The warning is: 警告是:

ISO C++ forbids variable length array 'people'

which is correct. 哪个是对的。 The use of variable length arrays is a GCC extension, which is turned off by -pedantic . 可变长度数组的使用是GCC扩展,由-pedantic关闭。 Note that successful compilation with -std=whatever does not guarantee your code complies with that standard - the - std flag is used to turn features on, not disable them. 注意与成功编译-std=whatever不保证你的代码与标准相关-的- std标志用于开启功能上,而不是禁用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM