编写一个在C和C ++中产生不同结果的程序
在这里,我们将看到一些程序,如果它们是用C或C++编译器编译的,它们将返回不同的结果。我们可以找到许多这样的程序,但是在这里我们正在讨论其中的一些程序。
在C和C++中,字符文字被视为不同的方式。在C中,它们被视为int,但在C++中,它们被视为字符。因此,如果我们使用sizeof()运算符检查大小,则它将在C中返回4,在C++中返回1。
C的现场演示。
示例
#include<stdio.h>
int main() {
printf("The character: %c, size(%d)", 'a', sizeof('a'));
}输出(C)
The character: a, size(4)
C的现场演示。
示例
#include<stdio.h>
int main() {
printf("The character: %c, size(%d)", 'a', sizeof('a'));
}输出(C++)
The character: a, size(1)
在C语言中,如果我们使用struct,则在使用它时必须使用struct标记,直到使用了某种typedef。但是在C++中,我们不需要使用struct标签来使用结构。
C的现场演示。
示例
#include<stdio.h>
struct MyStruct {
int x;
char y;
};
int main() {
struct MyStruct st; //struct tag is present
st.x = 10;
st.y = 'd';
printf("Struct (%d|%c)", st.x, st.y);
}输出(C)
Struct (10|d)
C++现场演示。
示例
#include<stdio.h>
struct MyStruct{
int x;
char y;
};
int main() {
MyStruct st; //struct tag is not present
st.x = 10;
st.y = 'd';
printf("Struct (%d|%c)", st.x, st.y);
}输出(C++)
Struct (10|d)
在C和C++中,布尔类型数据的大小不同。
C的现场演示。
示例
#include<stdio.h>
int main() {
printf("Bool size: %d", sizeof(1 == 1));
}输出(C)
Bool size: 4
C++现场演示。
示例
#include<stdio.h>
int main() {
printf("Bool size: %d", sizeof(1 == 1));
}输出(C++)
Bool size: 1
热门推荐
6 怎么说祝福语简短
10 祝福语大全简短赞美同学
11 婚庆花篮祝福语简短大气
12 出阁祝福语简短句子
13 形容新年的祝福语简短
14 新年祝福语长篇文案简短
15 药店祝福语简短10字
16 圆圆的祝福语简短
17 女朋友考试祝福语简短
18 新婚贺词简短的祝福语