Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a valid C statement?

Tags:

c++

c

gcc

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?

like image 555
Quixotic Avatar asked Dec 31 '10 21:12

Quixotic


2 Answers

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.

like image 76
Ben Voigt Avatar answered Sep 20 '22 23:09

Ben Voigt


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.

like image 39
tperk Avatar answered Sep 18 '22 23:09

tperk