operation on 'i' may be undefined

4.2k views Asked by At

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.

2

There are 2 answers

5
chux - Reinstate Monica On BEST ANSWER

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.

3
The Paramagnetic Croissant On

The reason is that both sides of the assignment depend on the value of i, however, you are modifying i in the statement and there's no sequence point between the two uses of i. According to the C standard, this results in undefined behavior.

To fix this warning, change the line in question to

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

By the way, you could use pointers instead of explicit indices, that would probably make the code a bit more readable:

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

    *n = *++str - '0';
}