ที่นี่เราจะเห็นบางโปรแกรมที่จะให้ผลลัพธ์ที่แตกต่างกันหากคอมไพล์ในคอมไพเลอร์ C หรือ C++ เราสามารถพบโปรแกรมดังกล่าวได้มากมาย แต่ที่นี่เรากำลังพูดถึงบางโปรแกรมอยู่
- ในภาษา C และ C++ อักขระตามตัวอักษรถือเป็นลักษณะที่แตกต่างกัน ใน C จะถือว่าเป็น int แต่ใน C++ จะถือว่าเป็นอักขระ ดังนั้นหากเราตรวจสอบขนาดโดยใช้ตัวดำเนินการ sizeof() มันจะคืนค่า 4 ใน C และ 1 ใน C++
ตัวอย่าง
#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 หากเราใช้ struct เราต้องใช้แท็ก struct เมื่อเราใช้งานจนกว่าจะใช้ typedef บางตัว แต่ใน 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