12

Can you think of 'a program' which gives 'different outputs for a C and a C++ compilers' (yet gives consistent output under the same language)?

caf
  • 233,326
  • 40
  • 323
  • 462
Aditya369
  • 545
  • 1
  • 7
  • 27

7 Answers7

20

Incompatibilities between ISO C and ISO C++

A common example is sizeof('A'), which is usually 4 in C but always 1 in C++, because character constants like 'A' have the type int in C but the type char in C++:

#include <stdio.h>

int main(void)
{
    printf("%d\n", sizeof('A'));
}
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
20

This program produces 12 in C++ or C99, and 6 in C89:

#include <stdio.h>

int main()
{
    int a = 12//**/2;
    ;

    printf("%d\n", a);
    return 0;
}
caf
  • 233,326
  • 40
  • 323
  • 462
  • although exact, I look at it more as a hack :) Nice one though. – Matthieu M. Mar 29 '11 at 06:40
  • 1
    That doesn't really answer the question, though, does it? It produces the same output in C and C++ (C99 is, after all, the current C standard). – Keith Thompson Oct 17 '11 at 05:09
  • @KeithThompson: Yes, [ecik's answer](http://stackoverflow.com/questions/5467576/different-output-for-different-compiler-c-and-c/5469636#5469636) is a more accurate match for the question. – caf Oct 17 '11 at 05:15
9
int main() { return sizeof 'a'; }
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • 2
    But not perfectly portable. `sizeof 'a'` could be 1 in C if `sizeof (int) == 1` (which is possible only if `CHAR_BIT >= 16`). – Keith Thompson Oct 17 '11 at 05:05
5
typedef char X;
int main() {
    struct X { double foo; }
    printf("%d\n", sizeof(X));
    return 0;
}
Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • 1
    Missing `#include `. `"%d"` requires an `int`, not a `size_t`. A conforming implementation could have `sizeof (struct X) == 1` (with, for example, `CHAR_BIT == 64`), fixable by giving `struct X` two `char` members instead of a `double`. – Keith Thompson Jan 02 '12 at 18:47
4

From wikipedia, altered to produce consistent output in each language:

extern int T;

int size(void)
{
    struct T {  int i;  int j;  };

    return sizeof(T) == sizeof(int);
    /* C:   return 1
    *  C++: return 0
    */
}
caf
  • 233,326
  • 40
  • 323
  • 462
ecik
  • 819
  • 5
  • 11
3
int class;

Will not compile in C++ and will compile in C.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
2
#include <stdio.h>
int main(void)
{
#ifdef __cplusplus
    puts("C++");
#else
    puts("C");
#endif
    return 0;
}
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631