鲜为人知但可能让你惊讶的C语言事实

1作者: whyandgrowth3 个月前原帖
虽然C语言是最古老且研究最广泛的编程语言之一,但它仍然有一些许多开发者可能不知道的奇特之处和历史遗留问题: 1. 性能的未定义行为: C语言故意包含了未定义行为(UB),例如有符号整数溢出或解引用空指针。这并不是一个错误,而是一种设计选择。通过将行为定义为未定义,编译器可以进行激进的优化。例如,它们可以假设有符号整数永远不会溢出,从而删除处理该情况的“死代码”,提高性能。 2. 变量声明模仿使用: 丹尼斯·里奇承认,C语言的声明语法(例如,int *p)可能会令人困惑,因为它反映了变量的使用方式。尽管这一点存在争议,他坚持认为这背后有一定的逻辑,将声明与变量的使用方式联系在一起。 3. 三字符和二字符序列: C语言曾支持“三字符序列”(如??=表示#)和“二字符序列”(如<:表示[),以帮助在缺乏某些符号的旧系统上实现可移植性。三字符序列在C23中被正式移除。 4. 结构体黑客与灵活数组成员: C语言程序员长期以来使用“结构体黑客”通过在结构体末尾添加一个零长度数组来创建可变长度的结构体。C99正式将这一做法规范化为灵活数组成员,使可变长度结构体得以官方支持。 即使在数十年后,C语言仍然隐藏着这些小秘密,揭示了它的历史和智慧。
查看原文
While C is one of the oldest and most studied programming languages, it still has some quirks and historical oddities that many developers might not know:<p>1. Undefined Behavior for Performance: C deliberately includes undefined behavior (UB) for things like signed integer overflow or dereferencing null pointers. This isn’t a bug—it’s a design choice. By leaving behavior undefined, compilers can make radical optimizations. For example, they can assume a signed integer never overflows and remove “dead” code handling that case, improving performance.<p>2. Variable Declarations Mimic Usage: Dennis Ritchie admitted that C’s declaration syntax (e.g., int *p) can be confusing because it mirrors the variable’s use. While controversial, he insisted there’s a certain logic behind it, tying declaration to how the variable is used.<p>3. Trigraphs and Digraphs: C once supported “trigraphs” (three-character sequences like ??= for #) and “digraphs” (two-character sequences like &lt;: for [) to help with portability on old systems lacking certain symbols. Trigraphs were officially removed in C23.<p>4. The Struct Hack &amp; Flexible Array Members: C programmers long used the “struct hack” to create variable-length structs by adding a zero-length array at the end of a struct. C99 formalized this with flexible array members, making variable-length structs officially supported.<p>Even decades later, C still hides these little gems that reveal both its history and its genius.