Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String assignment inside if else block?

Is this undefined behaviour? (Because the strings "True", "False" and "Error" only exit within the blocks and are destroyed when a block is exited):

char *p;
if (var1) {
    p = "True";
} else if (var2) { 
    p = "False";
} else {
    p = "Error";
}
printf("%s\n", p);

The same applies for the switch statement I guess. Then how could I express the logic above?

Sub question: Is this also undefined behaviour? :

struct bar {
    int i;
    double d;   
}

struct bar *barptr;
if (var1){
    barptr = &(struct bar) { 0, 0.0 };
} else {
    barptr = &(struct bar) { 5, 40.3 };
}
printf("%d", barptr->i);
like image 471
user10607 Avatar asked May 21 '26 15:05

user10607


1 Answers

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);
like image 171
Vlad from Moscow Avatar answered May 28 '26 06:05

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!