Explain about a piece of C code

Hello,

Could you please explain the below code? Why do we have these results?
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

int main()
{
	int i = 0, j =1 ,  k =2 , m;

	m = k++ || j++ || i++; // 1 0 1 3   How calculated?
	//m = i++ || j++ || k++; // 1 1 2 2   How calculated?
	printf("%d %d %d %d",m,i,j,k);

	return 0;
}
Two aspects to understand here
(1) What is the return value of "i++" if i = 0? Note: This is independent of the fact that i is incremented at some point.
(2) Look up boolean "short circuiting".
If you have a statement like:
1
2
3
4
5
6
7
bool foo()
{
    printf("foo!\n");
    return false;
}

int apple = true || foo();

"foo!" will never be printed, because the logical OR statement "short circuited" the logic, because it already knew that (true || anything) is true.
Last edited on
Get out your textbook and/or course notes and read about the operators being used.

varname++ is the post-increment operator.

|| is the logical-OR operator (meaning, it works on boolean values, which in C and C++ can be obtained from integers as:

  • zero → false
  • non-zero → true

Going the other way (boolean → int) gets you a value of 0 or 1.

Finally, C and C++ use short-circuit evaluation for (non-overloaded) logical operators. Hence, the very first (left → right) possible condition proving the truthiness of an expression is good enough for the entire expression.

Thus,

    m = 2 || 1 || 0
    m = true || true || false
    m = true
    m = 1

Likewise, each of i, j, and k is incremented by one, so after line 7 they equal 1, 2, and 3, respectively.
Topic archived. No new replies allowed.