有一些语法结构对 C 和 C++ 都有效,但在两种语言中编译和运行时行为不同。还可以利用一些差异来创建可以用两种语言编译但行为不同的代码。 例如,以下函数将在 C 和 C++ 中返回不同的值:
-
在 C 和 C++ 中都有效,但在编译时给出不同的答案:
// CPP program to demonstrate difference between // continue and break #include <iostream> using namespace std; main() { int i; cout << "The loop with break produces output as: /n"; for (i = 1; i <= 5; i++) { // Program comes out of loop when // i becomes multiple of 3. if ((i % 3) == 0) break; else cout << i << " "; } cout << "/nThe loop with continue produces output as: /n"; for (i = 1; i <= 5; i++) { // The loop prints all values except // those that are multiple of 3. if ((i % 3) == 0) continue; cout << i << " "; } }
输出结果:
4
C++中的实现:
// C++ code that is valid in both // C and C++ but produce different // behavior when compiled. #include <iostream> using namespace std; // extern keyword used for variable // declaration without define extern int S; // function for struct int differCAndCpp(void) { // create a structure struct S { int a; int b; }; // return sizeof structure // in c++ return sizeof(S); } // Main driver int main() { // call function differCAndCpp() printf("%d", differCAndCpp()); return 0; }
运行结果:
8
可以看到两个代码相同,但输出不同。这是因为 C 要求结构标记前面有 struct(因此 sizeof(S)
指代变量),但 C++ 允许省略它(因此 sizeof(S) 指代隐式 typedef)。
请注意,当 extern
声明放在函数内部时,结果是不同的:那么函数范围内同名标识符的存在会阻止隐式 typedef 对 C++ 生效,而 C 和 C++ 的结果将是 相同的。 另请注意,上面示例中的歧义是由于使用了带有 sizeof
运算符的括号。
使用 sizeof T
会期望 T 是一个表达式而不是一个类型,因此该示例不会给出与 C++ 相同的结果。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/264219.html