There is no any undefined behaviour. String literals have the static storage duration.
There is only invalid code (that was before you edited your post) because you forgot to specify a condition in statement
else if
According to the C Standard (6.4.5 String literals)
6 In translation phase 7, a byte or code of value zero is appended to
each multibyte character sequence that results from a string literal
or literals.78) The multibyte character sequence is then used to
initialize an array of static storage duration and length just
sufficient to contain the sequence
As for the compound literals then the code snippet indeed has undefined behaviour. According to the C Standard (6.5.2.5 Compound literals)
5 The value of the compound literal is that of an unnamed object
initialized by the initializer list. If the compound literal occurs
outside the body of a function, the object has static storage
duration; otherwise, it has automatic storage duration associated
with the enclosing block.
Take into account that there must be
barptr = &(struct bar) { 0, 0.0 };
The code snippet would be valid if you would write
struct bar {
int i;
double d;
};
struct bar bar;
if (var1){
bar = (struct bar) { 0, 0.0 };
} else {
bar = (struct bar) { 5, 40.3 };
}
printf("%d", bar.i);
char *ptr is (if not undefined) certainly unwise behaviour, as it might result in people attempting to write to it. Usechar const *instead.char *? Only to point at (iterate over) an array of chars?char *to point only to arrays of characters that you can alter.