开发者

MinGW GCC compiles a faulty code without warning or error

开发者 https://www.devze.com 2023-02-23 03:58 出处:网络
Can you explain to me why doesn\'t MingW GCC produce warning in this code: int main() { int num; int people[ num ];

Can you explain to me why doesn't MingW GCC produce warning in this code:

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

But here, I only replaced the last st开发者_StackOverflowatement with num = 1 and now there is a warning...

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. It just creates a single element array. In the second case since you actually use the num, it gives the error


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. 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. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消