-4
int x = 1,y = 1,z = 1;

++x || ++y && ++z;

printf("%d%d%d",x,y,z);

it is giving the output of 2,1,1. But how these unary operators and logical operators are working to give such a result i cant understand. Whether only unary operator working only for first case and not for others. C doesnot ave any boolean datatype also. Please help me with my problem.

Santhosh Pai
  • 2,535
  • 8
  • 28
  • 49
  • 1
    In `C`, if you have `exp1 || exp2` and `exp1` is "truthy" (which `2` is truthy), then it won't bother executing `exp2` since `||` means OR. Operator precedence dictates that `++x||++y&&++z` will behave as `++x||(++y&&++z)`. So only `x` will be incremented. The expression `++y&&++z` is skipped. – lurker Mar 18 '15 at 02:54
  • duplicate of [Why does `++x || ++y && ++z` calculate `++x` first, even though operator `&&` has higher precedence than `||`](https://stackoverflow.com/q/3700352/995714) – phuclv Aug 18 '18 at 11:25

1 Answers1

1

lurker's answer above is correct.

|| and && are short circuit operators.

Equivalent code is:

if(! ++x ) {
    if( ++y ) {
        ++z;
    } 
}
Community
  • 1
  • 1
iceraj
  • 359
  • 1
  • 5