问题
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.
回答1:
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.
回答2:
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';
}
来源:https://stackoverflow.com/questions/26961858/operation-on-i-may-be-undefined