【发布时间】:2011-07-24 23:10:45
【问题描述】:
你能想到“一个程序”,它为“C 和 C++ 编译器提供不同的输出”(但在同一语言下提供一致的输出)?
【问题讨论】:
-
这是一个愚蠢的面试问题
标签: c++ c compilation
你能想到“一个程序”,它为“C 和 C++ 编译器提供不同的输出”(但在同一语言下提供一致的输出)?
【问题讨论】:
标签: c++ c compilation
来自wikipedia,经过修改以在每种语言中产生一致的输出:
extern int T;
int size(void)
{
struct T { int i; int j; };
return sizeof(T) == sizeof(int);
/* C: return 1
* C++: return 0
*/
}
【讨论】:
#include <stdio.h>
int main(void)
{
#ifdef __cplusplus
puts("C++");
#else
puts("C");
#endif
return 0;
}
【讨论】:
此程序在 C++ 或 C99 中生成 12,在 C89 中生成 6:
#include <stdio.h>
int main()
{
int a = 12//**/2;
;
printf("%d\n", a);
return 0;
}
【讨论】:
typedef char X;
int main() {
struct X { double foo; }
printf("%d\n", sizeof(X));
return 0;
}
【讨论】:
#include <stdio.h>。 "%d" 需要 int,而不是 size_t。符合要求的实现可以有sizeof (struct X) == 1(例如CHAR_BIT == 64),可以通过给struct X 两个char 成员而不是double 来修复。
Incompatibilities between ISO C and ISO C++
一个常见的例子是sizeof('A'),它在 C 中通常是 4,但在 C++ 中总是 1,因为像 'A' 这样的字符常量在 C 中的类型为 int,而在 C++ 中的类型为 char:
#include <stdio.h>
int main(void)
{
printf("%d\n", sizeof('A'));
}
【讨论】:
sizeof 返回 size_t 而不是 int。所以你的代码包含错误。 stackoverflow.com/questions/940087/…
sizeof (int) 可能是 1。
int main() { return sizeof 'a'; }
【讨论】:
sizeof (int) == 1,sizeof 'a' 在 C 中可能是 1(只有在 CHAR_BIT >= 16 时才有可能)。
int class;
不会在 C++ 中编译,而是在 C 中编译。
【讨论】: