Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operation on 'i' may be undefined [duplicate]

I have this code to take a string of the form bla_2 and separate it:

void separate(char* str, char* word, int* n) {
    int i = 0;
    while(str[i] != '_') {
        word[i] = str[i++];
    }
    *n = str[++i] - '0';
}

I got:

warning: operation on ‘i’ may be undefined [-Wsequence-point]

But I am only changing i via ++ operator, I am not assigning anything to.

So, why is the UB, if it is? If not, how to get rid of the warning?

Notice that in my opinion, this question handles a different issue.

like image 458
gsamaras Avatar asked Feb 11 '23 13:02

gsamaras


1 Answers

word[i] = str[i++]; is a problem.

It is compiler's choice if i in word[i] is access before or after i is incremented in str[i++];

Do the i++ after the assignment

word[i] = str[i];
i++;

Further while(str[i] != '_') likely should be

while(str[i] != '_' && str[i] != '\0')

to prevent buffer overrun.

like image 79
chux - Reinstate Monica Avatar answered Feb 16 '23 03:02

chux - Reinstate Monica