Quixotic
Quixotic

Reputation: 2464

Is this a valid C statement?

Let's say I write char c[99] = {'Stack Overflow'}; in C or C++. It compiles fine but is this valid? By valid I meant not invoking any kind of undefined or unspecified behavior.

Again if I write char c[99] = 'Stack Overflow'; gcc complains about multicharacter constant which is obvious but in the above when I am enclosing within curly brackets compiler is happy! Why is it so?

I also notice that puts(c); after the first statement will output 'w' precisely the last character of a general string in-place of Stack Overflow. Why so?

Could somebody explain these behaviors separately?

Upvotes: 6

Views: 688

Answers (2)

tperk
tperk

Reputation: 91

Agreed - in Windows Kernel code - you see a lot of tagging memory. And it's actually implemented per platform. However, they use ULONGs to tag memory, and it's always a 4-character literal in reverse order: ULONG tagMemory = 'kscf';

The interpretation is platform-specific, but a stream of characters.

Upvotes: 1

Ben Voigt
Ben Voigt

Reputation: 283634

They both are only a single literal, so c[0] gets set to the literal and c[1] ... c[98] get filled with zero (NUL character).

I think what value actually gets stuffed into c[0] is implementation dependent, but it should at least compile on any compliant compiler.

EDIT: Verified against the standard, in C++0x at least:

A multicharacter literal has type int and implementation-defined value.

And in C99 (using the draft, cause it's free):

The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

Upvotes: 14

Related Questions