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()'
Advertisement
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP