ที่นี่เราจะเห็นความไม่ลงรอยกันระหว่าง C และ C ++ รหัส C บางรหัสที่สามารถคอมไพล์ได้โดยใช้คอมไพเลอร์ C แต่ไม่สามารถคอมไพล์ในคอมไพเลอร์ C++ และยังส่งกลับข้อผิดพลาด
- เราสามารถกำหนดฟังก์ชันโดยใช้ไวยากรณ์ ซึ่งระบุประเภทอาร์กิวเมนต์หลังรายการอาร์กิวเมนต์หรือไม่ก็ได้
ตัวอย่าง
#include<stdio.h>
void my_function(x, y)int x;int y; { // Not valid in C++
printf("x = %d, y = %d", x, y);
}
int main() {
my_function(10, 20);
} ผลลัพธ์
x = 10, y = 20
ผลลัพธ์
Error in C++ :- x and y was not declared in this scope
- ในภาษา C หรือเวอร์ชันเก่ากว่าของ C++ ประเภทตัวแปรเริ่มต้นคือจำนวนเต็ม แต่ใน C++ ที่ใหม่กว่า จะทำให้เกิดข้อผิดพลาด
ตัวอย่าง
#include<stdio.h>
main() {
const x = 10;
const y = 20;
printf("x = %d, y = %d", x, y);
} ผลลัพธ์
x = 10, y = 20
ผลลัพธ์
Error in C++ :- x does not name a type y does not name a type
- ในภาษา C ออบเจ็กต์ข้อมูลส่วนกลางอาจถูกประกาศหลายครั้งโดยไม่ต้องใช้คีย์เวิร์ดภายนอก คอมไพเลอร์ C พิจารณาเพียงครั้งเดียวสำหรับการประกาศหลายครั้ง
ตัวอย่าง
#include<stdio.h>
int x;
int x;
int main() {
x = 10;
printf("x = %d", x);
} ผลลัพธ์
x = 10
ผลลัพธ์
Error in C++ :- Redefinition of int x
- ในภาษา C เราสามารถใช้ void pointer เป็นตัวดำเนินการทางขวามือของงานที่มอบหมายหรือเริ่มต้นตัวแปรของตัวชี้ประเภทใดก็ได้
ตัวอย่าง
#include<stdio.h>
#include<malloc.h>
void my_function(int n) {
int* ptr = malloc(n* sizeof(int)); //implicitly convert void* to int*
printf("Array created. Size: %d", n);
}
main() {
my_function(10);
} ผลลัพธ์
Array created. Size: 10
ผลลัพธ์
Error in C++ :- Invalid conversion of void* to int*
- ในภาษา C หากไม่ได้ระบุประเภทอาร์กิวเมนต์ เราสามารถส่งอาร์กิวเมนต์ได้หลายรายการ
ตัวอย่าง
#include<stdio.h>
void my_function() {
printf("Inside my_function");
}
main() {
my_function(10, "Hello", 2.568, 'a');
} ผลลัพธ์
Inside my_function
ผลลัพธ์
Error in C++ :- Too many arguments to function 'void my_function()'