Reputation: 18299
I have came across a piece of code making the following initialization:
static const uint8_t s[] = {"Some string"};
I would expect it to be interpreted as follows: The right side is matching an array of char pointers with single element which points to a string literal "Some string". While the left part is an array of uint8_t
. Then the behavior I would expect is that the first element of s
to receive some truncated value of the pointer to the string literal, thus causing unexpected behavior in the following code, assuming s
is a string.
I've made the following test code:
#include <stdint.h>
#include <stdio.h>
static const uint8_t s1[] = "String1";
static const uint8_t s2[] = { "String2" };
int main(void){
printf("%p, %p\n", s1, s2);
printf("%s, %s\n", s1, s2);
return 0;
}
For my surprise it seems that it is not happening. Not only the code will work correctly, but also the disassembly shows that both s1
and s2
are initialize as the corresponding strings in identical way.
Is this something gcc
specific? Is C syntax permitting taking the single string literal into {}
and still interpret it as a string literal?
Upvotes: 10
Views: 3522
Reputation: 15804
The sun qingyao's answer correctly mentions that you can add extra braces to such initializer. It's worth to mention this does not only apply to arrays:
int x = { 0 };
compiles even though the element being initialized is not an array. This is thanks to the following clause:
6.7.9.11 The initializer for a scalar shall be a single expression, optionally enclosed in braces.
But why would such thing be allowed? The answer is, this makes possible to initialize values with a single syntax:
T x = { 0 };
works for any T
and zero-initializes everything (for structs, every member, for arrays, every element, for scalar types, just initializes the value).
Upvotes: 9
Reputation: 16097
Quoted from N1570 (the final draft of C11), 6.7.9 Initialization (emphasis mine):
- An array of character type may be initialized by a character string literal or UTF-8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
Upvotes: 17