編寫一個在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