문제

#include <stdio.h>

int main()
{
    int y = 1;
    if (y & (y = 2))
        printf("true \n");

    else
        printf("false \n");
        return 0;
}

Output:

true

In this program there is an undefined behaviour. The output is always true. I've tried few compilers. Can anyone explain me why it is true all the time?

도움이 되었습니까?

해결책

Because observed behavior is not defined behavior. The compilers you're using seem (by observation solely) to be performing the following:

  1. Assign y = 2
  2. Eval result of step (1)
  3. Eval y
  4. Bitwise-AND the results of steps (2) and (3) above.
  5. Eval result from step (4)

The result would be (2 & 2), which is true. The problem is, the order of 1-2, then 3 is not standard-defined. It could just as easily be this:

  1. Eval y
  2. Assign y = 2
  3. Eval result of step (2)
  4. Bitwise-AND the results of steps (1) and (3) above.
  5. Eval result from step (4)

The result would be (1 & 2), which is false

Or it could be something else entirely. Not all compilers will do the first, and you cannot assume because the compilers you used do, they all will. Nor can you assume that because they do and you observed that behavior, it is therefore defined; it isn't. Compilers don't define behavior; the standard does, and compilers are obliged to comply.

Note: there is a loophole in this era of definition, but it is not the norm, and even it is loosely defined by the standard. You will find areas within the standard the say something is "implementation-defined." In such cases the standard points out these areas of divergence with reasonably clarity. In such cases you should consult your implementation for definitive conclusion as to what behavior to expect, and in so doing be prepared to accept the simple a fact that such behavior can only be relied on within the confines of the implementation. This (your sample) is not such loophole exception.

My clang 3.5 rig seems (by my observation) to run the second sequence, not the first, and I could take your road and assume that "all" the compilers I tried (one of them) behave like that, therefore it is defined to be so. I would be mistaken to do so, as are you in your assumption.

Undefined behavior is just that; undefined.

다른 팁

You are trying to modify the value of y more than once between sequence points. There is not a standard way on how to handle that behavior. So:

i = i++; // gives undefined behavior also

valter

Yes, the code will always return True Because any non-zero value in any conditional statement is True(C-99 above) or 1(C-99) in C

if (y & (y = 2))
    printf("true %d\n");

In the if condition 2 is assigned to y first and then 2 is bitwise &'ed with 2. i.e. 0010 & 0010 it'll return 0010 as a result.

So now you have:

if(2)  //Any non-zero value is true
    printf("true %d\n");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top