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.
Related
int num;
scanf("%d", &num);
if (num % 4 == 0 && num%100 != 0 || num % 400 == 0)
printf("%d", 1);
else
printf("%d", 0);
In this logic, I found I do not need to do () in AND condition which is in front of OR condition.
if (*(num % 4 == 0 && num%100 != 0)* || num % 400 == 0)
It's only needed if (num % 4 == 0 && num%100 != 0 || num % 400 == 0) without () in front of OR condition.
so, it seems (A && B || C) works like ((A && B) || C)
but it seemed it could work as (A && (B || C)) condition.
Why is () not needed in this situation? A and B condition are automatically grouped from the beginning?
All operators in C (and in fact all languages) have what's called operator precedence which dictates which operands are grouped first.
The logical AND operator && has a higher precedence than the logical OR operator ||, which means that this:
A && B || C
Is the same as this:
(A && B) || C
So if you want B || C to be grouped together, you need to explicitly add parenthesis, i.e.:
A && (B || C)
Parentheses decide order of operations, if you move the parentheses around you may change what the output is. In the same way that (A + B) / C is different from A + (B / C) but still a valid equation.
See Order of Operations in C
Logical AND has higher priority than OR:
https://en.cppreference.com/w/c/language/operator_precedence
dg
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.
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.
Why does this following program print "Yes" instead of "No"?
None of the variables is initialized to 2.
bool hello = 0;
int a = 1;
int b = 3;
int c = 4;
int d = 5;
if (a || b || c || d == 2) {
hello = 1;
}
if (hello == 1) {
printf("Yes");
}
if (hello == 0) {
printf("No");
}
return 0;
}
The statement
if (a || b || c || d == 2)
is equivalent to:
if (a != 0 || b != 0 || c != 0 || d == 2)
The equality comparison does not automatically distribute across all the variables. If you want to do that, you need to perform all the comparisons explicitly:
if (a == 2 || b == 2 || c ==2 || d == 2)
The expression (a || b || c || d == 2) evalutates to true because it treats a, b, c as booleans, and any non-zero integer is true.
You have given logical operator in the expression It means that if non zero value came then the expression is true. Then hello=1 is set and in next f statement it prints YES
You just meet the short circuit behavior of logical expressions OR.
The order of evaluation of logical OR || is left to right.
So in the following expression:
left || right
if left = true then right will never going to be executed (short circuit). In your code exactly same happened.
As you know, any non zero value treated as true in C, hence, a which is 1 is true. So, take a look:
if (a || b || c || d == 2)
if (true || bla bla bla) //rights are not even checked!
if (true)
hello = 1;
Tada! So the program print "Yes"!
None of the variables is initialized to 2.
Yes of course! But your if condition is not going to check that. To do so, try this:
if (a == 2 || b == 2 || c ==2 || d == 2) {
//...
because if judge num is not zero , if think this is true. so your code
if (a || b || c || d == 2)
like
if ( true || true || true || false)
the result is true, programe print "YES"
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));
}