views:

167

answers:

4

According to my memory the following piece of code should compile fine on C++ but not in C. Only problem is how to test it? It compiled fine with g++ and also with gcc. I'm assuming that g++ is C++ compiler and gcc is C compiler. I've tried it with mingw under Windows. Am I correct? if not then how to compile it using C compiler.

int main() {
 const int i = 1;
 const int j = 2;
 const int k = 3;

 int array[i + j + k];
 return 0;
}
+11  A: 

No, that will compile in C99, which has support for variable length arrays. To get strict C89 behavior, try compiling with:

gcc -std=c89 -pedantic-errors

That gives:

error: ISO C90 forbids variable length array ‘array’

c89 means use C89, pedantic-errors means error on non-C89 code.

Matthew Flaschen
+2  A: 

The parameter for specifying a language with gcc is -x

from gcc --help on my system:

# -x <language>            Specify the language of the following input files
#                          Permissible languages include: c c++ assembler none
#                          'none' means revert to the default behavior of
#                          guessing the language based on the file's extension

However, your code is valid C code.

Otto Allmendinger
+1  A: 

It will compile in C++ and C99(but not in C89)

It compiled fine with g++ and also with gcc

gcc supports C99

if not then how to compile it using C compiler?

Chance the extension of the file from *.cpp to *.c.

Prasoon Saurav
GCC supports c89 as well. Compile with -ansi or -std=c89 flags.
N 1.1
compiling without such options defaults to C99.
Prasoon Saurav
Compiling without such option defaults to "GNU C" or "GNU C++", the meaning of which depends upon the version of GCC.
Alok
+3  A: 

It's legal in recent versions of C, either C99 or gcc extensions. Use the pedantic and standard options to restrict the accepted syntax:

peregrino:$ gcc -pedantic -std=c89 src/maybe_pedantic.c 
src/maybe_pedantic.c: In function ‘main’:
src/maybe_pedantic.c:6: warning: ISO C90 forbids variable length array ‘array’
Pete Kirkham