I have the following code snippets, and was somewhat confused by the output, based on my knowledge of how logical operators work. From what I know(based on truth tables in electronics),
- For logical
AND
,TRUE
andTRUE
gives a value ofTRUE
and all other combinations of the truth table givesFALSE
. - For logical
OR
, onlyFALSE
andFALSE
gives a value ofFALSE
. While all other combinations of the truth table givesTRUE
.
Based on this knowledge, this first code snippet-
void main( )
{
int i = -1, j = 1, k ,l ;
k = i && j ;
l = i || j ;
printf ( "%d %d\n", i, j ) ;
printf("%d %d", k,l);
}
gives the output-
-1 1
1 1
I am confused here because according to truth tables of logical AND and OR, the value of k should be -1. This comes from the fact that value of i
is -1
(which is FALSE
) and j
is 1
(which is TRUE
), so TRUE
AND
FALSE
should equal to FALSE
, that is, -1
.
However, since the output was 1 for both k and l
, I'm thinking that C processes logical AND
and OR
based on only 1 and 0 where 1 would be TRUE
and 0 would be false
. According to this logic, any non-zero value would be TRUE, so even -1
would be TRUE
.
In that case, k=i&&j
would mean -1&&1
. Since -1 and 1 are both TRUE, so the expression k= i&&j
evaluates to TRUE
, ie, 1. Following the same logic, l=i||j
also evaluates to TRUE
.
Am I correct in thinking that the second approach is the correct way in which logical operators work in C?
My second question is about the next code snippet-
void main( )
{
int j = 4, k ;
k = !5 && j ;
printf ( "\nk = %d", k ) ;
}
which produces the output k=0
This has really got me stumped, because I can't figure out how a Logical NOT
works within a Logical AND
operator. Here j
is 4
, but what is the value of k
, and how does this compare with j
? I'm thinking since k is not 5
, it could be -5
? But in that case, -5
and 4
both evaluate to TRUE
, so the value of k
should be 1
.
Please help.