1

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
}
user2805620
  • 125
  • 1
  • 1
  • 13

2 Answers2

1

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;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • Ok, so I know that the compiler is letting me know that but can you please explain in more detail why its undefined? I'm really new to programming. And is there a huge difference between using k++ and ++k? – user2805620 Oct 15 '13 at 00:17
  • 1
    @user2805620 `k++` returns the pre-increment value. `++k` returns the post-increment value. – chux - Reinstate Monica Oct 15 '13 at 00:19
  • So say k = 1, k++ would return 1 and ++k would return 2? And when I did use k = k++, I still get my desired output, although that is bad practice, is that just the tolerance of the c programming language? – user2805620 Oct 15 '13 at 00:39
  • @user2805620 It gets into more subtle issues involving "sequence points". Because of the "tolerance of the C language", one can get differing answers on different compiles. Thus is _may_ work to your satisfaction in this compile, hence the _warning_ versus an _error_. In general, C warnings are like a sign (with no fence) I saw at the edge of the Grand Canyon: "Persons who have gone beyond this sign have died." – chux - Reinstate Monica Oct 15 '13 at 01:32
1

refer to this link Undefined Behavior and Sequence Points

k = k++; // k is modified more than once
Community
  • 1
  • 1
amyangfei
  • 96
  • 1
  • 6