Piece of code that compiles with gcc but not g++ [

2019-09-12 01:41发布

问题:

Possible Duplicates:
Is this a legitimate C++ code?
“C subset of C++” -> Where not ? examples ?

Could anybody come up with a piece of code that compiles with gcc or any other C compiler, and doesn't compile g++ or any other C++ compiler?

UPDATE: I don't mean just keywords

UPDATE2: Thank you All for answers. Apparently moderators were less enthusiastic than I was about subtle differences between C and C++.

UPDATE3: to moderators: could you merge it with my previous question on the topic, as you suggested? It makes perfect sense to keep these two question together.

回答1:

#include <stdlib.h>

int main()
{
    char* s = malloc(128);
    return 0;
}

This will compile with gcc, but not with g++. C++ requires an explicit cast from void* here, whereas C does not.



回答2:

int main(int argc, char **class)
{
    return !argc;
}

Edit: another example

int foo();
int main(void) {
    return foo(42);
}
int foo(int bar) {
    return bar - 42;
}


回答3:

Try

extern int getSize();

int main()
{
    char x[getSize()];
    x[0] = 0;
}

int getSize()
{
     return 4;
}

Remember to compile with the strict flags.

> gcc -pedantic -std=c99 t.c
> g++ -pedantic t.c
t.c: In function `int main()':
t.c:6: error: ISO C++ forbids variable length array `x'


回答4:

How about

/* Within a function */
{
  enum {foo} bar;
  bar++;
}

That seems a pretty big breaking change in the design of C++, but it is what it is.



回答5:

What about character size:
Even worse is that it compiles but produces different output at runtime.

#include <stdio.h>

int main()
{
    fprintf(stdout, "%s\n", (sizeof('\xFF') == sizeof(char))?"OK":"Fail");
}

> gcc -pedantic t.c
> ./a.exe
Fail
> g++ -pedantic t.c
> ./a.exe
OK

This actually makes we wonder why this works?

fprintf(stdout, "%c%c\n", 'A', 'B');

It works on both compilers even though the size of the objects are different.



回答6:

pointer arithmetics on void*:

void* t;
t++; // compiles only in gcc