無法在 C++ 中編譯的 C 程式
C++ 語言是在 C 語言的基礎上添加了一些額外的特性,例如面向物件的特性。大多數 C 程式也可以使用 C++ 編譯器進行編譯。不過,也有一些程式無法使用 C++ 編譯器編譯。
讓我們來看一些可以在 C 編譯器中編譯,但不能在 C++ 編譯器中編譯的程式碼。
在這個程式中,對於 C++ 程式碼,會出現一個編譯錯誤。因為它試圖呼叫一個之前未宣告的函式。但在 C 中,它可能會編譯透過。
C 語言線上演示。
示例
#include<stdio.h>
int main() {
myFunction(); // myFunction() is called before its declaration
}
int myFunction() {
printf("Hello World");
return 0;
}輸出(C)
Hello World
輸出(C++)
[Error] 'myFunction' was not declared in this scope
在 C++ 中,普通指標不能指向一些常量變數,但在 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++ 中,當我們想要將其他型別的指標(如 int*、char*)賦值給 void 指標時,必須顯式地進行型別轉換,但在 C 中,如果它沒有進行型別轉換,它也會編譯透過。
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++ 中,我們必須初始化常量變數,但在 C 中,它可以在沒有初始化的情況下編譯透過。
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++ 中,我們不能使用這個名稱作為變數名,因為在 C++ 中,'new' 是一個關鍵字。它用於分配記憶體空間。
C 語言線上演示。
示例
#include<stdio.h>
int main() {
int new = 10;
printf("new: %d",new);
}輸出(C)
new: 10
輸出(C++)
[Error] expected unqualified-id before 'new' [Error] expected type-specifier before ')' token
我們無法在 C++ 中編譯以下程式碼。當我們嘗試將 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 作為 main() 的返回值型別,但在 C++ 中,我們必須使用 int 作為 main() 的返回值型別。
C 語言線上演示。
示例
#include<stdio.h>
void main() {
printf("Hello World");
}輸出(C)
Hello World
輸出(C++)
[Error] '::main' must return 'int'
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP