c++ - 解释 "C fundamentally has a corrupt type system"

标签 c++ c type-systems

在书中Coders at Work (p355),Guy Steele 谈到 C++:

I think the decision to be backwards-compatible with C is a fatal flaw. It’s just a set of difficulties that can’t be overcome. C fundamentally has a corrupt type system. It’s good enough to help you avoid some difficulties but it’s not airtight and you can’t count on it

他将类型系统描述为“腐败”是什么意思?

你能用一个简单的 C 例子来演示吗?

编辑:

  1. 这句话听起来颇有争议,但我并不想这么做。我只是想明白他的意思。

  2. 请用 C 而不是 C++ 给出示例。我也对“基本”部分感兴趣:)

最佳答案

C 中非类型安全的明显示例来自于您可以从 void * 转换为任何类型而无需显式转换的事实。

struct X
{
  int x;
};

struct Y
{
  double y;
};

struct X xx;
xx.x = 1;
void * vv = &xx;
struct Y * yy = vv; /* no need to cast explicitly */
printf( "%f", yy->y );

当然 printf 本身并不是完全类型安全的。

C++ 不是完全类型安全的。

struct Base
{
   int b;
};

struct Derived : Base
{
  int d;

  Derived() 
  {
     b = 1;
     d = 3;
  }
};

Derived derivs[50];
Base * bb = &derivs[0];
std::cout << bb[3].b << std::endl;

将 Derived* 转换为 Base* 没有问题,但是当您尝试将 Base* 用作数组时会遇到问题,因为它会使指针算术完全错误,而所有 b 值都是 1,您可能会很好得到一个 3(因为整数会变成 1-3-1-3 等)

关于c++ - 解释 "C fundamentally has a corrupt type system",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124810/

相关文章:

c++ - std::optional 是如何工作的?

haskell - 是否可以对 haskell 类型变量进行不等式约束?

scala - 依赖方法类型有哪些引人注目的用例?

c++ - 在 C++ 类中使用位域的未对齐属性

c++ - 如何检查文件是否存在(无论其文件类型如何)?

c++ - Qt: QHostAddress: 没有这样的文件或目录

在 C 中编译多个源

c - opengl glDrawElements 问题

c - 在 C 中替换字符串中的字符并随后取消替换的最佳方法

rust - 了解Rust和类型系统