โปรแกรมบางตัวคอมไพล์ได้ใน C และ C++ แต่ให้ผลลัพธ์ต่างกัน นี่คือตัวอย่าง:
- Character literals: ใน C เป็น int (ขนาด 4 ไบต์) ใน C++ เป็น char (ขนาด 1 ไบต์) sizeof('a') ใน 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 <iostream>
int main() {
printf("The character: %c, size(%d)", 'a', sizeof('a'));
}
เอาต์พุต C++
The character: a, size(1)
- Struct tag: ใน C ต้องใช้ struct tag (เช่น struct MyStruct st;) ใน C++ ไม่ต้อง (MyStruct st;)
ตัวอย่าง C
#include <stdio.h>
struct MyStruct { int x; char y; };
int main() {
struct MyStruct st; // ต้องมี struct tag
st.x = 10; st.y = 'd';
printf("Struct (%d|%c)", st.x, st.y);
}
ตัวอย่าง C++
#include <iostream>
struct MyStruct { int x; char y; };
int main() {
MyStruct st; // ไม่ต้องมี struct tag
st.x = 10; st.y = 'd';
printf("Struct (%d|%c)", st.x, st.y);
}
- Boolean size: ใน C sizeof(1==1) = 4 (int) ใน C++ = 1 (bool)
ตัวอย่าง C
#include <stdio.h>
int main() { printf("Bool size: %d", sizeof(1 == 1)); }
เอาต์พุต C
Bool size: 4
ตัวอย่าง C++
#include <iostream>
int main() { printf("Bool size: %d", sizeof(1 == 1)); }
เอาต์พุต C++
Bool size: 1