编写一个可以在C和C++中编译并运行的程序,但是在由C和C++编译器编译时会产生不同的结果。
可以有很多这样的程序,以下是其中一些。
1)字符文字在C和C++中的处理方式有所不同。在C字符文字中,如“ a”,“ b”,.. etc等被视为整数,而在C++中被视为字符。
例如,以下程序在C中生成sizeof(int)作为输出,而在C++中生成sizeof(char)。
#include int main() { printf("%d", sizeof('a')); return 0; }
2)在C语言中,每当声明struct变量时都需要使用struct标记。在C++中,不需要struct标记。例如,学生结构。在C语言中,我们必须对学生变量使用“ struct Student”。在C++中,我们可以省略struct并仅使用“ Student”。
以下是基于事实的程序,并在C和C++中产生不同的输出。它在C中打印sizeof(int),在C++中打印sizeof(struct T)。
#include int T; int main() { struct T { double x; }; // In C++, this T hides the global variable T, // but not in C printf("%d", sizeof(T)); return 0; }
3)布尔结果的类型在C和C++中是不同的。
// output = 4 in C (which is size of int) printf("%d", sizeof(1==1)); // output = 1 in c++ (which is the size of boolean datatype) cout << sizeof(1==1);