在这里,我们将看到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 typey 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()'
以上就是c和c++之间的不兼容性的详细内容。
