プログラミング言語Cにおける配列添字演算子(array subscript operator)[]
の伝統的かつ奇妙な言語仕様に関して、次期C2yをターゲットとした仕様修正が提案されている。小ネタ以外の使い道もなく修正されて良い頃合いかもね?*1
const char msg[] = "Hello"; const char *p = msg + 1; assert( 1[msg] == 'e' ); // OK: msg[1]と等価 assert( msg[-1] != 0 ); // NG: 未定義動作 assert( p[-1] == 'H' ); // OK: *(p-1)と等価 // N3352 2.2.1 Option1適用後 // 式 E[N] の E は配列型/ポインタ型のいずれか assert( 1[msg] == 'e' ); // NG: ill-formed // 配列型Eと整数定数Nの場合は0≦N assert( msg[-1] != 0 ); // NG: ill-formed assert( p[-1] == 'H' ); // OK: *(p-1)と等価
C23(N3220) 6.5.3.2/p2より引用(下線部は強調)。C90/C99/C11/C17でも同様。
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(counting from zero).
C Rationale 6.5.2.1より一部引用。
The C89 Committee found no reason to disallow the symmetry that permits
a[i]
to be written asi[a]
.
関連URL
*1:C言語 FAQ 日本語訳, 6章 配列とポインター, 6.11: 「このとんでもない交換可能性は、よくC言語について扱う文章の中で、誇らしく思うかのように記述されているが国際難解Cプログラムコンテスト以外では役に立たない。」