behavior of print function inside a Boolean expression [duplicate] - c

This question already has answers here:
What is short circuiting and how is it used when programming in Java? [duplicate]
(5 answers)
Closed 2 years ago.
language: C
a bool expression outputs 0 if 0 is entered, else 1 will be the output.
following the above statement,
CASE 1:
input
#include <stdio.h>
#include <stdbool.h>
main()
{
int a = 1,
b = 2;
bool res = ((a == b) && ("your "));
printf("res = %d", res);
}
output
res = 0
CASE 2:
input
bool res = (!(a == b) && ("your "));
printf("res = %d", res);
output
res = 1
CASE 3:
now i add prinf function to ("your ")
input
bool res = ((a == b) && printf("your "));
printf("res = %d", res);
output
res = 0 //adding printf doesn't change the output
CASE 4:
input
bool res = (!(a == b) && printf("your "));
printf("res = %d", res);
output
your res = 1 // i expected just "res = 1" not "your res = 1"
how is the print function not executed in CASE 3 but executed in CASE 4?

According to the C Standard (6.5.13 Logical AND operator)
4 Unlike the bitwise binary & operator, the && operator guarantees
left-to-right evaluation; if the second operand is evaluated, there is
a sequence point between the evaluations of the first and second
operands. If the first operand compares equal to 0, the second
operand is not evaluated.
In the expression used as an initializer in this declaration
bool res = ((a == b) && printf("your "));
the first operand (a == b) of the logical AND operator evaluates to 0. So the second operand that is the call of printf is not evaluated,
On the other hand, in this expression used as an initializer in the declaration
bool res = (!(a == b) && printf("your "));
the first operand !(a == b) evaluates to 1. So the second operand that is the call of printf is also evaluated.

The evaluation of logical and operator && is short-circuit evaluation.
Considering A && B, firstly A is evaluated. When A is true, A && B can become true and B is evaluated. When A is false, A && B will never be true and B is not evaluated.
Now look at actual cases.
In CASE 3 (a == b) && printf("your "), (a == b) is false because a (1) is not equal to b (2). Therefore now we lost all chance for the expression (a == b) && printf("your ") to become true and therefore printf("your ") is not evaluated. This means the function is not executed.
In CASE 4 !(a == b) && printf("your "), !(a == b) is true because (a == b) is false. Now the expression !(a == b) && printf("your ") may become true depending on the value of printf("your "), so printf("your ") is evaluated and the function is executed.

In Case 3:
It is due to compiler optimizing the statement. The statement is translated and evaluated from left to right because of the usage of parentheses. The first expression is: (a == b) is false because of the values of a and b. The compiler figured out that the result of the expression in ((a == b) && printf("your")) will always yield false. So optimization dictates not to generate code for printf("your").
I bet if you compile this in demode mode, you will see the expected result.
Explanation of case 4 is left for yourself. It is obvious. (hint pay attention to the precedence of the operators "!", "&&")
Good luck.

Related

why does the value of num2 in below expression becomes -1 instead of 0?

The below C program gives output -1 for num2. I do not understand why. Can somebody help me with it?
#include <stdio.h>
int main(void)
{
int num1 = 0, num2 = -1, num3 = -2, num4 = 1, ans;
ans = num1++ && num2++ || ++num4 && num3++;
printf("%d %d %d %d %d", num1, num2, num3, num4, ans);
return 0;
}
output:
1 -1 -1 2 1
The expression num1++ && num2++ || ++num4 && num3++ is parsed as:
(num1++ && num2++) || (++num4 && num3++)
Both || and && use shortcut evaluation, meaning that the right operand if and only if the left operand evaluates to false (resp. true).
num1++ && num2++ is evaluated first:
num1++ is evaluated: it evaluates to the initial value of num1, 0 and num1 is incremented.
since the left operand if false, the right operand of && is not evaluated (num2 is unchanged`) and the expression is false:
num1++ && num2++ is false, so the right operand of || must be evaluated to determine the value of the whole expression:
++num4 is evaluated: the value is 2 and num4 is incremented.
the left operand of this second && operator is true, so the right operand is evaluated
num3++ is evaluated: the value is -2 and num3 is incremented.
2 && -2 is true, the whole expression evaluates to true, which has type int and the value 1 in C: ans receives the value 1.
printf outputs 1 -1 -1 2 1 (without a trailing newline)
If the left side of a logical AND && is false, the right side will not be evaluated as the result can be determined as false already.

Logical && operators

if ((a % 5) && (a % 11))
printf("The number %d is divisible by 5 and 11\n", a);
else
printf("%d number is not divisible by 5 and 11\n", a);
How will the logical && operator work if I don't add == 0 in the expression, if there is no remainder, will it look for the quotient? and the quotient will always be a non zero term so the programme will always return true.
In your code
if ((a % 5) && (a % 11))
is the same as
if ( ((a % 5) != 0) && ((a % 11) != 0 ) )
Any non-zero value is taken as TRUTHY.
According to the C Standard (6.5.13 Logical AND operator)
3 The && operator shall yield 1 if both of its operands compare
unequal to 0; otherwise, it yields 0. The result has type int.
In the expression used in the if statement
if ((a % 5) && (a % 11))
if each operand a % 5 and a % 11 is unequal to 0 then the expression evaluates to logical true. That is when a is not divisible by 5 and is not divisible by 11 then the expression evaluates to true and as a result a wrong message is outputted in this statement
printf("The number %d is divisible by 5 and 11\n", a);
To make the output correct you should change the expression in the if statement the following way. Pay attention to that you need also to change the message in the second call of printf.
if ((a % 5 == 0) && (a % 11 == 0 ))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
printf("The number %d is divisible by 5 and 11\n", a);
else
printf("%d number is either not divisible by 5 or by 11\n", a);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#Saurav's answer best describes about your problem. In addition to it, if you want a solution in case you are not in mood to add == 0, then you could just simply use ! (NOT) operator:
if (!(a % 5) && !(a % 11))
Now it will show divisible only when both of the expression has zero values (i.e. no remainder - like the number 55).

What is the difference between if(a == (1,2)) and if(a == 1,2)?

What is the difference betweenif(a == (1,2)) and if(a == 1,2) ?
#include<stdio.h>
int main()
{
int a = 2;
if(a == (1,2))
printf("Hello");
if(a == 1,2)
printf("World");
return 0;
}
a == 1,2 is equivalent to (a == 1),2 due to operator precedence
And because of how the comma operator works, (a == 1),2 will result in 2. And a == (1,2) will be the same as a == 2.
So in effect your two conditions are like
if (a == 2)
printf("Hello");
if(2)
printf("World");
The first condition will be true only if a is equal to 2. The second condition will always be true (only zero is false).
In the both conditions of the if statements there is used the comma operator
The second condition is equivalently can be rewritten like
if( ( a == 1 ), 2)
The value of the comma operator is the value of the second operand. So the condition in the second if statement will always evaluate to true because 2 is not equal to 0.
The condition in the first if statement can be rewritten like
if(a == 2)
because the first expression (the integer constant 1) of the comma operator has no effect.
So the condition of the if statement evaluates to true only when a is equal to 2.

return statement with conditions ? and :

I am very beginner in c and I am reading now the classic example of the TicTacToe game.
I am not sure about what this return statement does:
{.....
return (ch == X) ?O :X;
This must be some conditional statement on the variable ch (that in my case stands for the player (X or O) but I am not sure about its meaning. Can anyone please tell me what does it do?
It means
if (ch == X)
return O;
else
return X;
This is called a ternary operator, because unlike many other operators, it doesn't take one or two operands, but three. A boolean condition and two values. In your example, if the boolean condition (ch == X) validates to true, O is the result of the operator. Otherwise, X is the result.
This can be rewritten as:
if (ch == X)
return O;
else
return X;
If ch equals X return O else return X.
The ... ? ... : ... operator is called ternary operator. Its a shorthand for simple if statement. Lets see few examples,
Odd/Even
n % 2 ? printf ("Odd") : printf ("Even");
OR
printf ("%s\n", n % 2 ? "Odd" : "Even");
Factorial
int factorial(int n)
{
return (n == 0 ? 1 : n * factorial (n - 1));
}

Operator precedence and ternary operator

I have a problem in C.
#include<stdio.h>
int main()
{
int a = 10, b = 0, c = 7;
if (a ? b : c == 0)
printf("1");
else if (c = c || a && b)
printf("2");
return 0;
}
This code prints 2 but I think a?b:c returns b=0 and 0==0 returns 1. Can you explain the code?
The conditional operator (?:) has one of the lowest precedences. In particular it is lower than ==. Your statement means this:
if(a ? b : (c == 0)) { ... }
Not this:
if((a ? b : c) == 0) { ... }
Your conditions are not properly written.
In the first if-statement:
if (a ? b : c == 0)
if you put the values, then it becomes
if(10 ? 0 : 7 == 0)
means, it will always return 0.
That's why control goes to the else part and there, it becomes
else if (7 = 7 || 10 && 0)
since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".
Now you want that code should return "1", then change your if statement in this way.
if( (a ? b:c) == 0){...}
because "==" operator has higher precedence than ternary operator.

Resources