我在很多书中读到C是C++的子集.

有些书说C是C++的子集,except for the little details.

在哪些情况下,代码可以用C编译,但不能用C++编译?

推荐答案

如果你比较C89C++,那么这里有几件事

在C++中没有试探性定义

int n;
int n; // ill-formed: n already defined

int[]和int[N]不兼容(C++中没有兼容类型)

int a[1];
int (*ap)[] = &a; // ill-formed: a does not have type int[]

没有K&R函数定义样式

int b(a) int a; { } // ill-formed: grammar error

嵌套 struct 在C++中具有类作用域

struct A { struct B { int a; } b; int c; };
struct B b; // ill-formed: b has incomplete type (*not* A::B)

无缺省整型

auto a; // ill-formed: type-specifier missing

C99增加了很多其他情况

在参数的数组维度中没有对声明说明符的特殊处理

// ill-formed: invalid syntax
void f(int p[static 100]) { }

没有可变长度数组

// ill-formed: n is not a constant expression
int n = 1;
int an[n];

没有灵活的数组成员

// ill-formed: fam has incomplete type
struct A { int a; int fam[]; }; 

没有用于帮助别名分析的限制限定符

// ill-formed: two names for one parameter?
void copy(int *restrict src, int *restrict dst);

C++相关问答推荐

int_leastX_t与intX_t不同吗?

C中的整字母后缀i是什么

有什么方法可以检测SunOS上的SparcWorks吗?

为什么在传输 Big Data 时共享内存段的运行时间比管道更长?

通过MQTT/蚊子发送大文件—限制在4MB

如何在C宏中确定Windows主目录?

如何判断宏参数是否为C语言中的整型文字

为什么在Linux(特别是Ubuntu 20.04LTS)上,POSIX共享内存对象在重启后仍然存在,然后突然变成了根用户?

为什么在此程序中必须使用Volatile关键字?

SDL 2.0-从数组渲染纹理

ARM64 ASIMD固有的加载uint8_t* 到uint16x8(x3)?

拥有3x3二维数组并访问数组[1][3]等同于数组[2][0]?

将数据移动到寄存器时出现分段故障

在创建动态泛型数组时,通过realloc对故障进行分段

这个C程序在工作中途停止获取输入.我收到分段故障(核心转储).我还是不知道问题出在哪里

为什么数组的最后一个元素丢失了?

使用TCL C API导航到列表中的元素

为什么我无法访问C语言中的文件

std::malloc/calloc/realloc/free 与纯 C 的 malloc/calloc/realloc/free 有什么不同

在 C/C++ 中原子按位与字节的最佳方法?