Logical Operators and increment operators

hemant vikas patnaik

Can anyone explain this code? How value is assigned to only variable m but the output is for all variables change. Also the roles of logical operator and increment operators over here.

#include <stdio.h>

#include <stdlib.h>
int main() 
{ 
    int i=-3, j=2, k=0, m; 
    m = ++i || ++j && ++k; 
    printf("%d%d%d%d\n", i, j, k, m); 
    return 0; 
}
Sourav Ghosh

|| or logical OR operator has a short-circuit property. It only evaluated the RHS is the LHS is FALSY.

In your case, the evaluation of ++x produces a value of -2, which is not FALSY (0). Hence, the RHS is never evaluated.

To break it down:

m = ++i || ++j && ++k; 

 >> m = (++i) || (++j && ++k);
     >> m = (-2) || (++j && ++k);
        >> m = 1   // -2 != 0 

So, only the value of m and i are changed, remaining variables will retain their values (as they are not evaluated).

That said, the result of the logical OR operator is either 0 or 1, an integer value. The result is stored in m, in your case.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related