C语言中指向数组首元素前一位置的指针及递减数组首元素指针的未定义行为:规则起源与历代标准定义查询
Let's break down these two questions about C pointer arithmetic undefined behavior clearly—they’re solid deep dives into the history of C standards!
1. Which C standard first defined that a pointer pointing to the position before the first array element is undefined behavior (UB)?
The earliest C standard to explicitly codify this as undefined behavior is ANSI C (C89, formally ISO/IEC 9899:1990).
In C89's section 6.3.6 (Additive Operators), the standard specifies:
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
A pointer targeting the position before an array’s first element falls outside the allowed range (array elements or one past the final element), so this was marked as UB starting with the first official C standard.
2. Is C17's 6.5.6/8 the first standard to define decrementing a pointer to the first array element as UB? How was this operation handled in earlier standards, and was it ever legal?
No, C17’s rule isn’t the first to cover this—every prior standardized version of C (C89, C99, C11) included nearly identical language restricting valid pointer arithmetic.
What earlier standards said:
- C89 (ISO/IEC 9899:1990): As noted above, section 6.3.6 requires pointer arithmetic results to land on an array element or one past the last element. Decrementing a pointer to the first element would put it outside this range, making the behavior undefined.
- C99 (ISO/IEC 9899:1999): Section 6.5.6/8 uses almost the exact wording as C17, stating that only pointers within the array or one past the final element are valid for arithmetic; any other result is UB.
- C11 (ISO/IEC 9899:2011): Section 6.5.6/8 mirrors the C99 and C17 language on this topic.
Was this operation ever legal?
Before the first ANSI standard, the original K&R C (from Kernighan & Ritchie’s 1978 book) had looser but still restrictive rules. K&R C only allowed pointer arithmetic within an array’s bounds (or one past the last element, for tasks like calculating array length via pointer subtraction). A pointer pointing before the first element was never considered valid—while K&R didn’t use the exact term "undefined behavior," such an operation was unpermitted and could lead to unpredictable results (which aligns with modern UB definitions).
To sum up: Decrementing a pointer to an array’s first element has never been a legal, well-defined operation in any standardized C version, nor in pre-standard K&R C.
内容的提问来源于stack exchange,提问作者Ilgiz Mustafin

