1

This is the exemplar code that I encountered in entry level Computer Programming course:

 #include <stdio.h>
 int main()
 {
     int l = 20, m = 10;
     int z;
     z= l++ || m++;
     printf("z = %d l = %d m = %d\n", z, l, m);
 }

The code prints l=21, m=10 and z=1 values of l and z are what was expected by me, but value of m is troubling me. Shouldn't it be 11 as m++ is present in code.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
aditya
  • 43
  • 5

3 Answers3

3

It is because m++ would only be executed if l++ == 0. Since l++ evaluates to 20 then m++ is never executed. If l was 0 initially then m++ would be executed.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
3
z= l++ || m++;

In your expression, l first assign value and after incremented one.

In Logical or (||) operation, If the left operand is non-zero, then right operand is not evaluated and the result is true. That's why l become 21 and m not evaluated and it's value is 10.

C standard(N1256 : 6.5.14-paragraph 4) say's:

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares unequal to 0, the second operand is not evaluated.

msc
  • 33,420
  • 29
  • 119
  • 214
  • You mean that it's evaluated first, right? – Iharob Al Asimi Feb 06 '17 at 11:45
  • @Iharob In logical AND operation, first check left operand value, If it's true then not check right operand value. – msc Feb 06 '17 at 11:47
  • @KeineLust Thank you for suggesting me. – msc Feb 06 '17 at 11:52
  • Nitpick: Whether the increment is done before the assignment or afterwards is unspecified. All the post-increment operator guarantees is that the value before the increment is yielded and the inrement is completed at the next sequence point. Oh, and C99 is **not** standard, it has been canceled with the release of C11 6 years ago. It does not make a difference here, but you should update your documentation anyway. – too honest for this site Feb 06 '17 at 12:10
1

What you see is called short circuit evaluation.

Your line here:

 z= l++ || m++;

Says, Check the value of l (increment while checking it). If l is non-0, set z to 1. If l is 0, check the value of m (increment while checking it). if m is non-0, set z to 1. Otherwise set z to 0.

Essentially, when the first of the two checks (l++) already evaluates true, there is no need for the system to check the second condition, so it doesn't, and thus also fails to increment m.

Magisch
  • 7,312
  • 9
  • 36
  • 52