Why does the compiler give me the warning that the operation on k may be undefined? What can I do to remove this warning?

int main(void){
    int k=0;
    int a,b;
    do{
       k = k++;
       printf("The value of k is: %d\n",k);
    }while(some condition that does not involve k);
return EXIT_SUCCESS
}
有帮助吗?

解决方案

The compiler is letting OP know the sequence k = k++; is not defined by C.

Some compilers may increment k and then assigned the pre-increment value to k - thus overwriting the increment. Another compiler may do the increment, but not yet save the result, assigned the pre-increment value to k, itself and then save the incremented value to k.

All in all, performing code like a = k++ / ++k; or the like, creates problems. The compiler is free to evaluate either the left or right side of the division first, the sequence is not defined, and the you get different answers.

Instead use:

k++;

or

++k;

or

k = k + 1;

其他提示

refer to this link Undefined Behavior and Sequence Points

k = k++; // k is modified more than once
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top