取自 http://www.ocf.berkeley.edu/~wwu/riddles/cs.shtml
它看起来非常适合我的编译器。不知道去哪里找?
最佳答案
1。滥用C++自动typedef
s
(请注意,struct
需要在内部范围内声明,以便在 C++ 中优先于外部名称。)
#include <stdio.h>
int main(void)
{
char x;
{
struct x { char dummy[2]; };
printf("%s\n", sizeof (x) == 1 ? "C" : "C++");
}
}
一个类似的版本,不依赖于 sizeof (type)
和 sizeof (variable)
之间的歧义,仅使用类型:
#include <stdio.h>
int main(void)
{
typedef char t;
{
struct t { char dummy[2]; };
printf("%s\n", sizeof (t) == 1 ? "C" : "C++");
}
}
2。滥用 C++ struct
/class
等价性、自动 typedef
和自动生成的默认构造函数
#include <stdio.h>
int isC = 0;
void Foo() { isC = 1; }
int main(void)
{
struct Foo { int dummy; };
Foo();
printf("%s\n", isC ? "C" : "C++");
}
3。滥用 C 中的嵌套 struct
声明
另见 Symbol clashing of inner and outer structs, C++ vs C
#include <stdio.h>
int main(void)
{
typedef struct inner { int dummy; } t;
{
struct outer { struct inner { t dummy[2]; } dummy; };
printf("%s\n",
sizeof (struct inner) == sizeof (t)
? "C++"
: "C");
}
}
4。滥用//
评论
这不适用于 C99 或支持 //
作为扩展的 C89 编译器。
#include <stdio.h>
int main(void)
{
printf("%s\n",
0 //* */
+1
? "C++"
: "C");
}
或者:
printf("%s\n",
1 //* */ 2
? "C++"
: "C");
5。 sizeof
与 char
文字的区别
请注意,这不能保证是可移植的,因为某些假设平台可能会使用超过 8 位的字节,在这种情况下 sizeof(char)
可能与 sizeof(int)
。 (另见 Can sizeof(int) ever be 1 on a hosted implementation?)
#include <stdio.h>
int main(void)
{
printf("%s\n", sizeof 'a' == 1 ? "C++" : "C");
}
6。执行左值⇒右值转换时的滥用差异
这是基于 ISO C++03 标准中的 5.16、5.17、5.18 示例,它适用于 gcc,但不适用于 MSVC(可能是由于编译器错误?)。
#include <stdio.h>
int main(void)
{
void* array[2];
printf("%s\n",
(sizeof (((void) 0), array) / sizeof (void*) == 1)
? "C"
: "C++");
}
7。滥用C和C++语法解析三元运算符的方式差异
这不是严格合法的,但有些编译器是松懈的。
#include <stdio.h>
int main(void)
{
int isCPP = 1;
printf("%s\n", (1 ? isCPP : isCPP = 0) ? "C++" : "C");
}
(您也可以检查 __cplusplus
预处理器宏(或各种其他宏),但我认为这不符合问题的精神。)
我在以下位置有所有这些的实现: http://www.taenarum.com/csua/fun-with-c/c-or-cpp.c
关于c++ - 编写一个程序,如果编译为 (ANSI) C 程序将打印 "C",如果编译为 C++ 程序将打印 "C++",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2038200/