Is this a valid C statement?

Let's say I char c[99] = {'Stack Overflow'}; writing char c[99] = {'Stack Overflow'}; in C or C ++. It compiles fine, but is it really? In fact, I meant not to refer to any type of undefined or undefined behavior.

Again, if I write char c[99] = 'Stack Overflow'; gcc complains about a multi-character constant that is obvious, but in the example above, when I enclose in curly braces, the compiler is happy! Why is this so?

I also notice that puts(c); after the first statement prints 'w', it is the last character of the common string instead of Stack Overflow . Why is that?

Can someone explain this behavior separately?

+6
c ++ c gcc
source share
2 answers

Both of them are only one literal, therefore c[0] set to a literal, and c[1] ... c[98] filled with zero (NUL character).

I think that some value is actually added to c[0] , it depends on the implementation, but it should at least compile on any compatible compiler.

EDIT: checked for compliance with the standard, in C ++ 0x:

A multi-page literal is of type int and has a value defined by the implementation.

And in C99 (using a draft , free it):

The value of an integer character constant containing more than one character (for example, 'ab' ) or contains a character or escape sequence that does not map to a single-byte executable character is determined by the implementation.

+14
source share

Agreed - in the Windows kernel code you see a lot of tagging memory. And it is actually implemented on the platform. However, they use ULONG to mark the memory and always have a 4-character literal in the reverse order: ULONG tagMemory = 'kscf';

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

+1
source share

All Articles