MinGW GCC compiles faulty code without warning or error

Can you explain to me why the MingW GCC does not generate a warning in this code:

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

But here I replaced the last expression 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; } 
+6
source share
2 answers

I think because you are using only the first element, it optimizes the number in the first example. It just creates one array of elements. In the second case, since you are actually using a number, it gives an error

+2
source

This code:

 #include <iostream> using namespace std; int main() { int num; int people[ num ]; cout << people[ 0 ]; cin >> num; } 

will throw an error (actually a warning) in g ++ if the -pedantic flag is -pedantic . Warning:

 ISO C++ forbids variable length array 'people' 

what is right. Using variable length arrays is a GCC extension that disables on -pedantic . Note that successfully compiling with -std=whatever does not guarantee that your code complies with this standard. The std flag is used to enable functions, not to disable them.

+1
source

Source: https://habr.com/ru/post/885616/


All Articles