-1
#include<stdio.h>
  void main()
  {
     int x=3,y=2,z=0,m;
     m=++x || ++y && ++z;
 printf("\n %d %d %d %d\n",x,y,z,m);  //  4  2  0  1
   } 

The output of the following code is mentioned as comment in program and I am trying to evaluate how this answer came but I am not able to understand.

I just wanted to know how the program calculates the relative value.

  • This will help you: https://en.cppreference.com/w/c/language/operator_precedence and this https://stackoverflow.com/questions/36879912/short-circuit-evaluation-with-both-operator – Eugene Sh. Oct 11 '18 at 14:00
  • 2
    `++x` has value 4 (and assigns 4 to `x` as a side-effect). `4 || ` has value `1` and does not evaluate ``. So your `m` gets `1`, your `x` gets `4`, your other variables aren't altered. – pmg Oct 11 '18 at 14:03
  • 1
    and this code just cannot be used in a serious program. – Jean-François Fabre Oct 11 '18 at 14:04
  • Basically if the left operand of `||` evaluates to true, everything on the right side is ignored. So you might as well write `m = ++x || y++ + ++y / 0 + *(int*)NULL;` and it will work just fine, since all the bugs on the right side of `||` are ignored. – Lundin Oct 11 '18 at 14:20
  • @Lundin: even behind a hiding contruct, `y++ + ++y` is still UB. The compiler itself can barf with that :) – pmg Oct 11 '18 at 14:26
  • @pmg Nope, or the compiler would barf over `type x = malloc(sizeof *x);` too, where `x` is an uninitialized variable and `*x` is a lvalue access. But just like as the case with `1 || ...`, the operand of sizeof isn't evaluated. – Lundin Oct 11 '18 at 15:00
  • Ok, if the compiler can prove `x` is always true (as it can in the present situation) then `x || y++ + ++y` is not UB. – pmg Oct 11 '18 at 15:09

1 Answers1

-2

thanks to pmg, i have corrected my original answer (i had an error)

Because the left side of the OR operator (||) is not zero, it doesn't evaluate anything else on that line. This is called a "short circuit operator". In this example you gave, the programmer basically is tricking the compiler. If the argument on the right of the operator does not affect the outcome, it will not execute that code. However in this case, there are increments going on there and they won't be evaluated either. This will assign "1" to m. your output should be 3, 2, 0, 1.

John Lord
  • 1,941
  • 12
  • 27
  • 3
    Nope, when the program sees `4 ||` it [*short-circuits* further evaluation](https://port70.net/~nsz/c/c11/n1570.html#6.5.14) and returns `1`; `y` or `z` do not "suffer" the increment. – pmg Oct 11 '18 at 14:11
  • i'll edit. thanks for that. – John Lord Oct 11 '18 at 14:16
  • @johnlord But is this has any relevance to the operator precedence?? – Pratik Kulkar Oct 11 '18 at 14:47
  • read the comment from pmg. The link explains it. the logical or prevents code to the right from running if the left side evaluates to something besides zero. – John Lord Oct 11 '18 at 15:04