C 與 C++ 的不相容性


這裡我們將看到 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 中,全域性資料物件可以多次宣告,而無需使用 extern 關鍵字。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 指標作為賦值的右側運算子,或初始化任何指標型別的變數。

示例

#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()'

更新於: 2019 年 7 月 30 日

124 次瀏覽

啟動你的 職業生涯

根據課程獲得認證

開始
Advertisement
© . All rights reserved.