代码在 C 和 C++ 中均有效,但会产生不同的输出
cc++server side programmingprogramming更新于 2024/9/10 8:39:00
这里我们将看到一些程序,如果在 C 或 C++ 编译器中编译,它们将返回不同的结果。我们可以找到许多这样的程序,但这里我们讨论的是其中的一些。
- 在 C 和 C++ 中,字符文字的处理方式不同。在 C 中,它们被视为 int,但在 C++ 中,它们被视为字符。因此,如果我们使用 sizeof() 运算符检查大小,它将在 C 中返回 4,在 C++ 中返回 1。
示例
#include<stdio.h> int main() { printf("字符: %c,size(%d)", 'a', sizeof('a')); }
输出
字符: a,size(4)
示例
#include<iostream.h> int main() { printf("字符: %c,size(%d)", 'a', sizeof('a')); }
输出 (C++)
字符:a,size(1)
在 C 中,如果我们使用 struct,那么在使用它时我们必须使用 struct 标记,直到使用某些 typedef。但在 C++ 中,我们不需要 struct 标记来使用结构。
示例
#include<stdio.h> struct MyStruct{ int x; char y; }; int main() { struct MyStruct st; //struct 标记存在 st.x = 10; st.y = 'd'; printf("Struct (%d|%c)", st.x, st.y); }
输出 (C)
Struct (10|d)
示例
#include<iostream> struct MyStruct{ int x; char y; }; int main() { MyStruct st; //struct 标签不存在 st.x = 10; st.y = 'd'; printf("Struct (%d|%c)", st.x, st.y); }
输出 (C++)
Struct (10|d)
C 和 C++ 中布尔类型数据的大小不同。
示例
#include<stdio.h> int main() { printf("Bool 大小: %d", sizeof(1 == 1)); }
输出 (C)
Bool 大小:4
示例
#include<iostream> int main() { printf("Bool 大小: %d", sizeof(1 == 1)); }
输出 (C++)
Bool 大小:1