程式碼在 C 和 C++ 中都是有效的,但會產生不同的輸出
此處我們將看到一些程式,如果在 C 或 C++ 編譯器中編譯,它們將返回不同的結果。我們可以找到許多此類程式,但此處我們將討論其中的部分程式。
- 在 C 和 C++ 中,字元字面量有不同的處理方式。在 C 中,它們被視為 int,而在 C++ 中,它們被視為字元。因此,如果我們使用 sizeof() 運算子檢查大小,它將在 C 中返回 4,在 C++ 中返回 1。
示例
#include<stdio.h>
int main() {
printf("The character: %c, size(%d)", 'a', sizeof('a'));
}輸出
The character: a, size(4)
示例
#include<iostream.h>
int main() {
printf("The character: %c, size(%d)", 'a', sizeof('a'));
}輸出 (C++)
The character: a, size(1)
在 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)
示例
#include<iostream>
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++ 中是不同的。
示例
#include<stdio.h>
int main() {
printf("Bool size: %d", sizeof(1 == 1));
}輸出 (C)
Bool size: 4
示例
#include<iostream>
int main() {
printf("Bool size: %d", sizeof(1 == 1));
}輸出 (C++)
Bool size: 1
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP