
在这里,我们将看到C和C++之间的一些不兼容性。一些可以使用C编译器编译的C代码,在C++编译器中无法编译。并且会返回错误。
- 我们可以使用一种语法来定义函数,该语法在参数列表之后可选择指定参数类型。
示例
#includevoid 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++中,会产生一个错误。
示例
#includemain() { 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编译器会将其视为多个声明中的一次。
示例
#includeint x; int x; int main() { x = 10; printf("x = %d", x); }
输出
x = 10
输出
Error in C++ :- Redefinition of int x
- 在C语言中,我们可以使用void指针作为赋值操作符的右操作数,或者用来初始化任何指针类型的变量。
示例
#include#include 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语言中,如果未指定参数类型,我们可以传递多个参数。
示例
#includevoid 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()'











