编写一个在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语言中,如果我们使用结构体,那么在使用它之前,我们必须使用结构体标签,除非使用了typedef。但在C++中,我们不需要结构体标签来使用结构体。
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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP