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

对着背影说爱祢 提交于 2020-01-06 08:38:06

问题


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


来源:https://stackoverflow.com/questions/4372328/piece-of-code-that-compiles-with-gcc-but-not-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!