开发者

Explain working of this C program

Please explain working in each case.

Why both cases have same output?

Case I:

int main (void)
{
    int i = 5;
    if(i == ++i)           //plz explain here How values are checked
       printf("Equal");
    else
      printf("Not Equal");

  return 0;
}
//Output: Equal;

Case II:

int main (void)
{
    int i = 5;
    if(++i == i)            //plz explain here How values are checked
       printf("Equa开发者_StackOverflow中文版l");
    else
      printf("Not Equal");

  return 0;
}
//Output: Equal;


Neither of those programs is valid; you are not allowed to read and update the same variable without a sequence point in between. Thus, it is undefined behavior what either of those programs will do, and so the fact that they may happen to return the same answer on your compiler and machine doesn't mean anything.


It is equal because this is C. As the other answer says, the result of this operation is undefined because you violate C rules -- which means that you cannot guarantee the same answer when switching compilers (although all compilers may be implemented similar, which doesn't make it a guarantee). The fact that C allows you to shoot yourself in the foot does not mean that it is good practice to do so.

Now, why does it work?

Conjecture #1:

i may be stored in a register, say r1, and the compiler may be compiling this entire comparison into one single CMP instruction, with an autoincrement addressing mode. Say it is CMP ++r1, r1 or CMP r1, ++r1, then depending on the actual CPU, both may return a true compare.

Conjecture #2:

The compiler may be compiling the compare into:

inc r1   // increment r1
CMP r1, r1   // compare with itself

Conjecture #3:

The compiler may be optimizing to always put a simple variable access to the right hand side. It is allowed to do that because the order of execution in a == operator is undefined and the compiler can rearrange things as it likes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜