yohhoyの日記

技術的メモをしていきたい日記

文字列リテラルは変更できないlvalue

C/C++言語では、文字列リテラル(string literal)は lvalue に分類される。ただし文字列リテラルの変更は未定義動作(undefined behavior)を引き起こす。文字列リテラル以外のリテラルは rvalue(prvalue) に分類される。

(通常の)文字列リテラル型は、C++ではconst char配列、Cではchar配列となる。

C++11以降

C++11(N3337) 2.14.5/p8, p12, 5.1.1/p1より一部引用。

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type "array of n const char", where n is the size of the string as defined below, and has static storage duration (3.7).

12 (snip) The effect of attempting to modify a string literal is undefined.

1 (snip) A string literal is an lvalue; all other literals are prvalues.

C++03以前

ISO C++03 2.14.3/p1-2, 5.1/p2より一部引用。

1 (snip) An ordinary string literal has type "array of n const char" and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. (snip)
2 (snip) The effect of attempting to modify a string literal is undefined.

2 (snip) A string literal is an lvalue; all other literals are rvalues.

C

C99 6.4.5/p5, 6.5.1/p4より一部引用。

5 (snip) For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence; (snip)
6 (snip) If the program attempts to modify such an array, the behavior is undefined.

4 A string literal is a primary expression. It is an lvalue with type as detailed in 6.4.5.

関連URL