ภาษา C++ ออกแบบมาโดยเพิ่มคุณสมบัติเชิงวัตถุเข้าไปใน C โปรแกรม C ส่วนใหญ่คอมไพล์ด้วย C++ ได้ แต่มีบางโปรแกรมที่คอมไพล์ไม่ผ่านใน C++
ดูโค้ดที่คอมไพล์ใน C ได้แต่ไม่ได้ใน C++:
โปรแกรมนี้มี compilation error ใน C++ เพราะพยายามเรียกฟังก์ชันที่ยังไม่ได้ประกาศ แต่ใน C คอมไพล์ได้
สำหรับ C:
ตัวอย่าง
#include<stdio.h> int main() { myFunction(); } int myFunction() { printf("Hello World"); return 0; }ผลลัพธ์ (C)
Hello World
ผลลัพธ์ (C++)
[Error] 'myFunction' was not declared in this scope
ใน C++ pointer ธรรมดาไม่สามารถชี้ไปที่ตัวแปร constant ได้ แต่ใน C ทำได้
สำหรับ C:
ตัวอย่าง
#include<stdio.h> int main() { const int x = 10; int *ptr; ptr = &x; printf("The value of x: %d", *ptr); }ผลลัพธ์ (C)
The value of x: 10
ผลลัพธ์ (C++)
[Error] invalid conversion from 'const int*' to 'int*' [-fpermissive]
ใน C++ ต้อง typecast เองเมื่อ assign void pointer ให้ int*, char* แต่ใน C ไม่ต้อง cast ก็คอมไพล์ได้
สำหรับ C:
ตัวอย่าง
#include<stdio.h> int main() { void *x; int *ptr = x; printf("Done"); }ผลลัพธ์ (C)
Done
ผลลัพธ์ (C++)
[Error] invalid conversion from 'void*' to 'int*' [-fpermissive]
ใน C++ ต้อง initialize constant variables แต่ใน C คอมไพล์ได้โดยไม่ init
สำหรับ C:
ตัวอย่าง
#include<stdio.h> int main() { const int x; printf("x: %d", x); }ผลลัพธ์ (C)
x: 0
ผลลัพธ์ (C++)
[Error] uninitialized const 'x' [-fpermissive]
ใน C ใช้ตัวแปรชื่อ 'new' ได้ แต่ใน C++ ไม่ได้เพราะ 'new' เป็น keyword สำหรับจัดสรรหน่วยความจำ
สำหรับ C:
ตัวอย่าง
#include<stdio.h> int main() { int new = 10; printf("new: %d", new); }ผลลัพธ์ (C)
new: 10
ผลลัพธ์ (C++)
[Error] expected unqualified-id before 'new'
ไม่สามารถคอมไพล์โค้ดนี้ใน C++ ได้ จะ error ตอนแปลง int เป็น char* แต่ใน C ทำงานได้
สำหรับ C:
ตัวอย่าง
#include<stdio.h> int main() { char *c = 123; printf("c = %u", c); }ผลลัพธ์ (C)
c = 123
ผลลัพธ์ (C++)
[Error] invalid conversion from 'int' to 'char*' [-fpermissive]
ใน C ใช้ void เป็น return type ของ main() ได้ แต่ใน C++ ต้องใช้ int
สำหรับ C:
ตัวอย่าง
#include<stdio.h> void main() { printf("Hello World"); }ผลลัพธ์ (C)
Hello World
ผลลัพธ์ (C++)
[Error] '::main' must return 'int'