07-27-2023, 11:35 AM
So, I was writing some code and I was getting an unexpected output in one part of my program which disrupted the entire system.
I managed to extract and simplify the problem to a basic logical expression. Let's say:
int i = 1, j = 1, k = 0;
printf("%d\n", ++i || ++j && k);
printf("%d, %d, %d\n", i, j, k);
return 0;
The output for this program is:
`1`
`2` `1` `0`
I am thinking that the value of `j` was not incremented to `2` due to the short circuit nature of the `||` operator. However I am confused how the value of the first `"%d"` is `1`. Shouldn't the value of `k` be non-zero for the `&&` statement to return `1`? Or isn't this statement executed at all since `++i || ++j` is not `0` and thus returns a `1`?
- I know that `&&` is a logical *and*, and *expr1* && *expr2* has the value 1 if values of *expr1* && *expr2* are **both** non-zero.
Any clarifications would be appreciated and please excuse the basic nature of this question.
I managed to extract and simplify the problem to a basic logical expression. Let's say:
int i = 1, j = 1, k = 0;
printf("%d\n", ++i || ++j && k);
printf("%d, %d, %d\n", i, j, k);
return 0;
The output for this program is:
`1`
`2` `1` `0`
I am thinking that the value of `j` was not incremented to `2` due to the short circuit nature of the `||` operator. However I am confused how the value of the first `"%d"` is `1`. Shouldn't the value of `k` be non-zero for the `&&` statement to return `1`? Or isn't this statement executed at all since `++i || ++j` is not `0` and thus returns a `1`?
- I know that `&&` is a logical *and*, and *expr1* && *expr2* has the value 1 if values of *expr1* && *expr2* are **both** non-zero.
Any clarifications would be appreciated and please excuse the basic nature of this question.