char array initialization: Is 'char a[] = ("a")' valid ANSI C?

  • Thread starter Petter Reinholdtsen
  • Start date
D

Dave Thompson

However, a string literal that (occurs where it) is evaluated produces
a distinctive kind of value -- an anonymous static-duration array that
may be shared, must not be written, but isn't const. Nothing else does
quite this, although C99 compound literals (or their GCC equivalent,
constructor expressions) are very close.
Thanks for the correction. How about "not with expressions that
contain a string literal and evaluate to an array of char or a
pointer to char"?
That doesn't limit it the way you want; it would include e.g.:
static char foo [7];
char (* bar (char * unused)) [7] { return &foo; }
* bar ("ABC") /* is a char array that you can access safely */
foo + strspn ("DEF", "ED") /* is a pointer, but into foo */

I have recently been trying "string literal value" as a term that is
technically correct if you parse carefully but also "intuitively"
clear and easy enough to read if you don't.

Is the following initialiser valid?

int a[] = { { 0 } }; /* 2 levels of braces */

It appears to be. The initializer for an aggregate can be a brace-
enclosed list of values (an initializer-list). That's the outer
braces. The list of values applies to the members of the aggregate,
so what we need inside the outer braces are initializers that are
allowed for "int". Since "[t]he initializer for a scalar shall be a
single expression, optionally enclosed in braces", the inner braces
shouldn't pose any problem. Am I missing something?
I'm not sure that's required. p11 is "for a scalar" and only "scalar
type" is actually defined. I'm not sure if p11 includes everything
that has scalar type, or only whole objects (variables); the immediate
opposition of p12 makes me think the latter.

It may well make good sense to implement subobject initializers
allowing the same things including extra braces as for scalar whole
objects, and I certainly see no constraint prohibiting it. OTOH I see
only very rare cases where there is any point in coding this way.

If you or anyone really cares, I suggest this would be better taken up
in c.s.c -- although they may well fall back on demanding a DR.

- David.Thompson1 at worldnet.att.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top