Basic Logical Operator Programming Exercise

I have a problem with a question in my book:

#include<stdio.h> void main() { int a=5, b=-7, c=0, d; d = ++a && ++b || ++c; printf("\n%d%d%d%d",a,b,c,d); } 

The question asks me what the code output is. I ran it and the result is on screen 6-601. I understand why a=6 and b=-6 , but I do not understand why c=0 and d=1 ?

+6
source share
2 answers

I believe that you have already received your answer, but just to reflect a little, let me add one more clarification. First, to quote the properties of the && and || , from C11 , chapters Β§6.5.13 and Β§6.5.13 respectively,

(I)

The && operator must give 1 if both its operands are compared not equal to 0; otherwise, it gives 0. [...] If the first operand compares equal to 0 , the second operand is not evaluated.

and

(Ii)

Operator || must give 1 if one of its operands is compared not equal to 0; otherwise it gives 0. [...]. If the first operand compares unevenly with 0 , the second operand is not evaluated.

and both guarantee a score from left to right. So, comparing your code,

 d = ++a && ++b || ++c; 

it happens like

 d = ((++a && ++b) || ++c ); 

which is rated as

 d = (( 6 && ++b ) || ++c); 

and then

 d = ( ( 6 && (-6) ) || ++c); 

Now in the previous step (I) is performed, and it reduces to

 d = ( 1 || ++c); 

Now, after an accent that already matches (II), therefore, no further evaluation of the operand RHS || (i.e. ++c not evaluated) and it looks like d = 1 and the final result 1 is stored in d .

That, a == 6 , b == -6 , c == 0 and d ==1 .


Having said that void main() should be changed to int main(void) , at least to conform to the standard.

+15
source

Operator || OR is shorted, which means that if the left side is true, then the right side is not evaluated. In this case, ++a && ++b is true, so ++c never starts and c keeps its value equal to zero.

In addition, since it evaluates to true, this is indicated by the character 1 , which is stored in d .

Any nonzero value is considered true, and the result of Boolean operations is defined as 0 or 1 as an integer.

+14
source

All Articles