-2

Please explain output of this program.

#include<stdio.h>

int main()
{
    int x=0;
    x ^= x || x++ || ++x || x++;

    printf("\n%d",x);
}

O/p is 3 (http://codepad.org/X49j0etz)

According to me output should be 2.
as || is a sequence point as far as i remember.
so expression becomes.

x ^= 0 || 0 || 2 || 2;

so after evaluation of this expression(x || x++ || ++x || x++;) x becomes 3
x  = 3 ^ 1
so x becomes 2;
Medo42
  • 3,821
  • 1
  • 21
  • 37
anshul garg
  • 473
  • 3
  • 7

2 Answers2

2

I'm pretty sure the answers claiming undefined behaviour are correct, but there is also a simple explanation for how you can arrive at the result of 3.

Just consider that the last x++ is never evaluated because the last || operation short-circuits, and let's assume that the side effects are applied before the ^= is evaluated. Then you are left with

x = 2 ^ 1;

Unsurprisingly resulting in 3.

Medo42
  • 3,821
  • 1
  • 21
  • 37
0

This is an undefined behavior in c. Because we cannot predict in which direction the expression is evaluated

Sorcrer
  • 1,634
  • 1
  • 14
  • 27