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)?
Asked
Active
Viewed 1,729 times
12
-
9This is a stupid interview question – BЈовић Mar 29 '11 at 07:47
7 Answers
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
-
1operator `sizeof` returns `size_t` not `int`. So your code contains error. http://stackoverflow.com/questions/940087/whats-the-correct-way-to-use-printf-to-print-a-size-t – UmmaGumma Mar 29 '11 at 19:20
-
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
-
-
1That 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
-
2But 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
-
1Missing `#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
*/
}
-
This returns a different status depending on the language, but it doesn't produce any *output*. – Keith Thompson Feb 19 '15 at 15:58
2
#include <stdio.h>
int main(void)
{
#ifdef __cplusplus
puts("C++");
#else
puts("C");
#endif
return 0;
}

Keith Thompson
- 254,901
- 44
- 429
- 631
-
-
@harper: Yes. It's section 6.10 of the C99 standard, section 16 of the C++ standard. – Keith Thompson Oct 17 '11 at 06:02