你可能不知道的 C 语言冷知识
1 分•作者: whyandgrowth•9 个月前
尽管 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 <: for [) to help with portability on old systems lacking certain symbols. Trigraphs were officially removed in C23.<p>4. The Struct Hack & 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.