return statement with conditions ? and : - c

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));
}

Related

behavior of print function inside a Boolean expression [duplicate]

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 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.

OR and less than operators not working as intended C language

I'm doing an exercise of a book called programming in C language, trying to solve exercise 7.9 and so my code works perfectly until I add a conditional statement for the function to only accept variables greater than 0
I have tried changing it in many ways but nothing seems to work
// Program to find the least common multiple
#include <stdio.h>
int main(void)
{
int lcm(int u, int v);
printf("the least common multiple of 15 and 30 is: %i\n", lcm(15, 30));
return 0;
}
// Least common multiple
int lcm(int u, int v)
{
int gcd(int u, int v);
int result;
if (v || u <= 0)
{
printf("Error the values of u and v must be greater than 0");
return 0;
}
result = (u * v) / gcd(u, v);
return result;
}
// Greatest common divisor function
int gcd(int u, int v)
{
int temp;
while (v != 0)
{
temp = u % v;
u = v;
v = temp;
}
return u;
}
I expect the output of lcm(15, 30) to be 30, but I keep getting an error, if a delete de if statement inside the lcm function it works fine, but I want the program to return an error if for example I use (0, 30)
if (v || u <= 0) is not saying "if v is less than or equal to zero OR if u is less than or equal to zero", like I believe you think it is. It's actually saying "if v is not zero, OR u is less than or equal to zero".
The operation a || b tests if a evaluates to non-zero, and if it doesn't, then it tests if b evaluates to non-zero. If either a or b is non-zero, then the expression is true.
In C, equality and relational operators like ==, !=, <, >, <= and >= produce the result 1 if the relation is true, and 0 if it is false, allowing you to use them in conditional expressions.
The correct conditional is:
if (v <= 0 || u <= 0)
if (v || u <= 0) considers v as a boolean variable so it is true for every non zero value. So your if is true for any non zero v.
Use if (v <= 0 || u <= 0)

Calculate prefix expression unix

I need to write a multi-process prefix expressions parser and evaluator.
Given a prefix expression such as the following on standard input
for instance: (+ (* (+ 2 4) 5) (- (- 6 7) 8)).
The program should read each sub-expressions in a forked process.
The parent process must wait until the child process has finished reading its sub-expression, and continue from there.
It is not illegal to use scanf or printf functions.
Totally useless, but maybe fun.
You start by doing this in one process only.
Add that multiprocess stuff.
As a hint, I show you how to do this in C++. You have to translate this into C yourself:
int read_sequence()
{
int y;
if ((cin>>ws).peek() == '('){
cin.ignore( 1 );
char op = cin.get();
y = read_sequence();
while ((cin>>ws).peek() != ')'){
int b = read_sequence();
y = op == '+' ? y + b
: op == '-' ? y - b
: op == '*' ? y*b
: y / b;
}
cin.ignore( 1 );
} else {
cin >> y;
}
return y;
}

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