0

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.

6
  • 2
    No, do your own homework
    – Falmarri
    Dec 7, 2010 at 0:32
  • maybe it looks like, but it's not. It's a natural continuation of a question I've just asked
    – matcheek
    Dec 7, 2010 at 0:35
  • You were given examples in the comment thread where you asked. Dec 7, 2010 at 0:36
  • I swear they were not there when I asked this question
    – matcheek
    Dec 7, 2010 at 0:37
  • @matcheek: fair enough, I think pts did edit the comment at least once. Dec 7, 2010 at 0:41

6 Answers 6

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

4
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;
}
1
  • OK the keyword class, but if we forget keywords about the keywords?
    – matcheek
    Dec 7, 2010 at 0:39
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'
2

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.

2

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.

1
  • 1
    works because all "small" integer types are promoted to int in any case when passed to a varag function. Dec 7, 2010 at 6:06
1

pointer arithmetics on void*:

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.