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