1

Increment operator not working.

I was learning C language expressions. I've also tried different combinations of increment operators (prefix and postfix) on the variables but the output is coming out to be same.

int i=-3, j=2 ,k=0,m;

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

printf("%d%d%d%d\n",i,j,k,m);  

I expect the output to be -2311 but it comes out to be -2301.

Ali Kanat
  • 1,888
  • 3
  • 13
  • 23
  • `k` isn't incremented because `||` short-circuits and doesn't execute the right hand side – Jean-François Fabre Feb 13 '19 at 14:12
  • 1
    Read about [*short-circuit evaluation*](https://en.wikipedia.org/wiki/Short-circuit_evaluation), which is employed by `&&` and `||`. And remember that any non-zero value is "true" while only `0` is "false". – Some programmer dude Feb 13 '19 at 14:12
  • related/dupe: https://stackoverflow.com/questions/628526/is-short-circuiting-logical-operators-mandated-and-evaluation-order – NathanOliver Feb 13 '19 at 14:15
  • You should probably read about [*operator precedence*](https://en.cppreference.com/w/c/language/operator_precedence) as well. – Some programmer dude Feb 13 '19 at 14:16
  • 1
    By the way, a good book or tutorial or class would have mentioned the short-circuit nature of the logical operators, as well as about operator precedence. So please go back to them and reread your books/tutorials/class-notes. – Some programmer dude Feb 13 '19 at 14:18
  • just to be sure: you shouldnt write such obfuscated code. Such snippets are good for learning, but once you got it you can stay away from such monster lines. The next one reading the code, might have the same problems you have now – 463035818_is_not_an_ai Feb 13 '19 at 14:23

2 Answers2

4

i and j are incremented because i needs to be evaluated. j also needs to be evaluated because i is non-zero.

But since this combined expression is non-zero, || short-circuits, and k++ is not evaluated or executed.

On the other hand, bitwise operators don't short-circuit. They also don't convert to booleans. If you want to evaluate all conditions and keep the same result you could write

m= (!!++i) & (!!++j) | (!!++k);

using the double negation trick to convert integer value to boolean.

Or spare another statement and simplify to (courtesy from user694733):

++i; ++j; ++k;
m = i && j || k;
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

The && and || operators short-circuit - depending on the value of the left-hand side of the expression, the right hand side may not be evaluated at all.

For the expression a || b, if a is non-zero, then the result of a || b is 1 regardless of the value of b, so b is not evaluated. For the expression a && b, if a is zero, then the result of a && b is zero regardless of the value of b, so b is not evaluated.

In your case, the result of ++i && ++j is non-zero, so ++k is not evaluated.

John Bode
  • 119,563
  • 19
  • 122
  • 198