c++ 输出 struct_编写一个在C和C++中产生不同结果的程序

434dcab40291c51efde33d92f49df30a.png

编写一个可以在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);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值