Hello everyone, my first post in your forum and from my questions you can assume correctly that i am under novice level.
I am trying to understand the short-circuit behavior of logical expressions so I made the following programm:
Code:
#include <stdio.h>
int main(void)
{
int i, j, k;
i = 3; j = 4; k = 5;
printf("variables are: i = %d, j = %d, k = %d\n", i, j, k);
printf("output of the expression i < j || ++j < k is: %d\n", i < j || ++j < k);
printf("variables are: i = %d, j = %d, k = %d\n", i, j, k);
return 0;
}
According of how I understand the operator precedence, the following should happen:
- ++j will increase to 5.
- i < j and j < k will evaluate next, resulting in 1 and 0 (I assume that in both expressions the j has the value of 5)
- 1 || 0 will evaluate last, resulting in 1.
First of all I would like to ask if my thinking is correct.
Next something strange appear to the output:
variables are: i = 3, j = 4, k = 5
output of the expression i < j || ++j < k is: 1
variables are: i = 3, j =
4, k = 5
I was expecting j = 5. In fact if i modify the expression and in place of the logical OR I put a logical AND "i < j && ++j < k" the output seems fine:
variables are: i = 3, j = 4, k = 5
output of the expression i < j && ++j < k is: 0
variables are: i = 3, j =
5, k = 5
Can someone help me understand why this occur?
I am using gcc compiler in windows 7 64bit in case this information helps.
I appreciate your time to read this.