2011-03-29 99 views

回答

19

此程序产生用C 12 ++或C99,和6在C89:

#include <stdio.h> 

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

    printf("%d\n", a); 
    return 0; 
} 
+0

尽管确切的说,我把它看作是一个黑客:)虽然不错。 – 2011-03-29 06:40:25

+1

但是,这并没有真正回答这个问题吗?它在C和C++中产生相同的输出(C99毕​​竟是当前的C标准)。 – 2011-10-17 05:09:20

+0

@KeithThompson:是的,[ecik's answer](http://stackoverflow.com/questions/5467576/different-output-for-different-compiler-c-and-c/5469636#5469636)是一个更准确的匹配题。 – caf 2011-10-17 05:15:23

3
int class; 

用C不会编译++和将在C.

+0

哇!很多想法都在一个地方......不错.. – Aditya369 2011-03-29 05:37:06

+1

问题是关于程序输出,而不是编译器输出。 – 2011-03-29 08:17:43

9
int main() { return sizeof 'a'; } 
+1

完美简洁! – GManNickG 2011-03-29 03:39:30

+2

但不完美的便携式。如果'sizeof(int)== 1'(只有在'CHAR_BIT> = 16'时才有可能)'sizeof'a''可以是1。 – 2011-10-17 05:05:30

20

Incompatibilities between ISO C and ISO C++

一个常见的例子是sizeof('A'),这通常是4 C,但总是1在C++编译,因为字符类似于'A'的常量在C中具有类型int,但在C++中具有类型char

#include <stdio.h> 

int main(void) 
{ 
    printf("%d\n", sizeof('A')); 
} 
+1

运算符'sizeof'返回'size_t'而不是'int'。所以你的代码包含错误。 http://stackoverflow.com/questions/940087/whats-the-correct-way-to-use-printf-to-print-a-size-t – UmmaGumma 2011-03-29 19:20:54

+0

和'sizeof(int)'可能是1. – 2012-01-02 18:48:44

5
typedef char X; 
int main() { 
    struct X { double foo; } 
    printf("%d\n", sizeof(X)); 
    return 0; 
} 
+1

缺少' #include '。 '“%d”'需要一个'int',而不是'size_t'。符合的实现可以有'sizeof(struct X)== 1'(例如'CHAR_BIT == 64'),通过给'struct X'两个'char'成员而不是'double'来解决。 – 2012-01-02 18:47:32

4

wikipedia,改变以产生在每一种语言一致的输出:

extern int T; 

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

    return sizeof(T) == sizeof(int); 
    /* C: return 1 
    * C++: return 0 
    */ 
} 
+0

这将根据语言返回不同的状态,但不会生成任何*输出*。 – 2015-02-19 15:58:14

2
#include <stdio.h> 
int main(void) 
{ 
#ifdef __cplusplus 
    puts("C++"); 
#else 
    puts("C"); 
#endif 
    return 0; 
} 
+0

预处理器是该语言的一部分吗? – harper 2011-10-17 05:45:01

+0

@harper:是的。它是C99标准的第6.10节,C++标准的第16节。 – 2011-10-17 06:02:06