Date: Sun, 29 Dec 2024 00:43:09 +0100
On 28/12/2024 00.51, Jāāā Gustedt wrote:
> Jens,
>
> on Sat, 28 Dec 2024 00:26:41 +0100 you (Jens Maurer via Liaison
> <liaison_at_[hidden]>) wrote:
>
>> const char s1[] = "abc"; // #1
>> const char s2[] = ("abc"); // #2
>>
>> #1 is the canonical way to initialize a character array with
>> a string literal, and is supported by both C and C++.
>>
>> Recently, a question came up whether #2 is valid, too.
>> C++ uses grammar non-terminals in this area of the specification,
>> and it seems pretty clear that parenthesized string literals don't
>> satisfy the rules, and thus #2 is ill-formed.
>>
>> C23 superficially has the same rules as C++ in this area,
>> but I'd appreciate some confirmation.
>
> The corresponding phrase only refers to string literals themselves
> (the syntax element) and not expressions, as would be a string literal
> enclosed in parenthesis, 6.7.11 p7, first sentence:
Ok, so we both have the same understanding of the C23 rules.
> The initializer for an array shall be either a string literal,
> optionally enclosed in braces, or a brace-enclosed list of
> initializers for the elements.
>
>> (Quite a few implementations appear to accept #2.
>
> do they ? I never would have suspected this to work.
Yes, unanimously so (as far as C++-related implementations
are concerned):
https://godbolt.org/z/EPTrn1PdG
Jens
> Jens,
>
> on Sat, 28 Dec 2024 00:26:41 +0100 you (Jens Maurer via Liaison
> <liaison_at_[hidden]>) wrote:
>
>> const char s1[] = "abc"; // #1
>> const char s2[] = ("abc"); // #2
>>
>> #1 is the canonical way to initialize a character array with
>> a string literal, and is supported by both C and C++.
>>
>> Recently, a question came up whether #2 is valid, too.
>> C++ uses grammar non-terminals in this area of the specification,
>> and it seems pretty clear that parenthesized string literals don't
>> satisfy the rules, and thus #2 is ill-formed.
>>
>> C23 superficially has the same rules as C++ in this area,
>> but I'd appreciate some confirmation.
>
> The corresponding phrase only refers to string literals themselves
> (the syntax element) and not expressions, as would be a string literal
> enclosed in parenthesis, 6.7.11 p7, first sentence:
Ok, so we both have the same understanding of the C23 rules.
> The initializer for an array shall be either a string literal,
> optionally enclosed in braces, or a brace-enclosed list of
> initializers for the elements.
>
>> (Quite a few implementations appear to accept #2.
>
> do they ? I never would have suspected this to work.
Yes, unanimously so (as far as C++-related implementations
are concerned):
https://godbolt.org/z/EPTrn1PdG
Jens
Received on 2024-12-28 23:43:15