Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ความไม่เข้ากันได้ระหว่าง C และ C++


ความไม่เข้ากันได้ระหว่าง C และ C++ โค้ด C บางอย่างคอมไพล์ใน C ได้แต่ไม่ได้ใน C++

  • นิยามฟังก์ชันด้วยไวยากรณ์ระบุชนิดอาร์กิวเมนต์หลังรายการอาร์กิวเมนต์

ตัวอย่าง

#include<stdio.h> void my_function(x, y) int x; int y; { printf("x = %d, y = %d", x, y); } int main() { my_function(10, 20); }

ผลลัพธ์ (C)

x = 10, y = 20

ผลลัพธ์ (C++)

Error: x and y was not declared in this scope
  • ใน C หรือ C++ เก่า default type เป็น int แต่ C++ ใหม่ error

ตัวอย่าง

#include<stdio.h> main() { const x = 10; const y = 20; printf("x = %d, y = %d", x, y); }

ผลลัพธ์ (C)

x = 10, y = 20

ผลลัพธ์ (C++)

Error: x does not name a type, y does not name a type
  • ใน C global data objects ประกาศซ้ำได้โดยไม่ต้อง extern C compiler นับครั้งเดียว

ตัวอย่าง

#include<stdio.h> int x; int x; int main() { x = 10; printf("x = %d", x); }

ผลลัพธ์ (C)

x = 10

ผลลัพธ์ (C++)

Error: Redefinition of int x
  • ใน C void pointer ใช้เป็น right-hand operand ของ assignment ให้ pointer ชนิดอื่นได้

ตัวอย่าง

#include<stdio.h> #include<malloc.h> void my_function(int n) { int* ptr = malloc(n * sizeof(int)); printf("Array created. Size: %d", n); } main() { my_function(10); }

ผลลัพธ์ (C)

Array created. Size: 10

ผลลัพธ์ (C++)

Error: Invalid conversion of void* to int*
  • ใน C ถ้า argument type ไม่ระบุ ส่งหลายอาร์กิวเมนต์ได้

ตัวอย่าง

#include<stdio.h> void my_function() { printf("Inside my_function"); } main() { my_function(10, "Hello", 2.568, 'a'); }

ผลลัพธ์ (C)

Inside my_function

ผลลัพธ์ (C++)

Error: Too many arguments to function 'void my_function()'