首頁  >  文章  >  後端開發  >  C和C++之間的不相容性

C和C++之間的不相容性

PHPz
PHPz轉載
2023-08-28 18:33:061081瀏覽

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, &#39;a&#39;);
}

輸出

Inside my_function

輸出

Error in C++ :- Too many arguments to function &#39;void my_function()&#39;

以上是C和C++之間的不相容性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除