문제

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