开发者

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 c开发者_JAVA百科urly 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜