First this is the question I'm working on:
Evaluate each of the following expressions in C:
int x=1, y=7, z=0;
char a='m';
1) a ? y-x : x–y
2) x = 5 ? (y = z) : (z = y)
I understand the rest of the questions but number (1) confuses me... isn't it supposed to be a logical expression?
I mean 'm' cannot be true nor false; how can I answer this question? Is it simply "Error"? Or is there something I missed?
For number (2) the statement (z=y) should execute which changes z to 7, but isn't it supposed to be x == 5 and I tried it on a terminal and it changes both x and y to 0.
What am I missing?
In C ANY numeric type can be evaluated as a bool, and for such types, any non-zero value is 'true'. So since the character 'm' is non-zero (only '\0' is zero), it is "true"
Precedence -- All operators in C have precedence, and ?:, while lower than most, is higher than assignment operators. So this expression is equivalent to:
x = (5 ? (y = z) : (z = y))
Related
I wanted to know if there's a way to omit second or third part of the ternary operator?
I already read this and similar ones but they didn't help.
What I specifically want is something like:
x == y ? x*=2;
however this gives me error as gcc expects another expression also. So are:
x == y ? x *=2 : continue;
x == y ?: x /=2;
What can I do in these situations except:
if(x == y) do_something;
Edit for further clarification:
As my question seems to be confusing and got all kinds of comments/answers my point was when thinking logically, an else is required after if , so is the default statement in a switch however, neither are mandatory. I was asking if it's the case with ?: also and if so, how.
I wanted to know if there's a way to omit second or third part of the ternary operator?
No, not in standard C.
You can substitute expressions or statements that do not use the conditional operator at all, but in standard C, the conditional operator requires three operands, just like the division operator (/) requires two. You cannot omit any.
Nor is it clear why you want to do. The primary thing that distinguishes the conditional operator from an if [/ else] statement is that expressions using the conditional operator are evaluated to produce values. If you're not interested in that value then using a conditional expression instead of a conditional statement is poor style. A standard if statement is much clearer, and clarity is king. This is a consideration even when you do want the value.
What can I do in these situations except:
if(x == y) do_something;
You can go have a coffee and hope the mood passes.
But if it doesn't, then the logical operators && and || have short-circuiting behavior that might suit, as #EricPostpischil already observed:
a && b is an expression analogous to if (a) b;. It evaluates a, after which there is a sequence point. If a was truthy then it evaluates b and that is the result of the expression; otherwise it does not evaluate b and the value of a is the value of the expression. That is the C version of the hypothetical a ? b : (nothing), and why C does not need the latter.
Similarly, a || b is an expression analogous to if (!a) b;. b is evaluated and yields the result of the expression if and only if a is falsey. That is the C version of the hypothetical a ? (nothing) : b.
But here again, it is poor C style to use && and || expressions exclusively for their side effects. If you don't care about the result of the operation, then use an if statement.
Or perhaps poor style is the point? If you're shooting for an entry in the International Obfuscated C Code Contest then abusing operators is par for the course. In that case, you could consider rewriting your expressions to use the ternary operator after all. For example,
x == y ? x *=2 : continue;
could be written as x *= ((x == y) ? 2 : 1), provided that you weren't actually trying to get loop-cycling behavior out of that continue. And
x == y ?: x /=2;
could be rewritten similarly. Though if you were actually looking toward IOCCC, then there are better obfuscation options available.
For the purpose asked about in this question, in which the result value of the conditional operator would not be used:
For a ? b : c without b you can use a && b, which will evaluate b if and only if a is true.
For a ? b : c without c you can use a || c, which will evaluate c if and only if a is false.
These expressions will have different values than a ? b : c, but that does not matter when the value is not used.
Without some exceptional circumstance to justify this, most experienced programmers would consider it bad practice.
GCC has an extension that uses the first operand for a missing second operand without evaluating it a second time. E.g. f(x) ? : y is equivalent to f(x) ? f(x) : y except that f is only called once.
Similar to the 'hyphen-ish' character of "-1" being called "unary minus", "?:" is called "trenary" because it requires 3 parts: the condition, the "true" case statement and the "false" case statement. To use "?:" you must supply 3 "terms".
Answering the question in the title, no, you cannot omit one part.
The following responds to "What can I do in these situations except:"
Given that your two examples show an interest in performing (or not) a mathematical operation on the variable 'x', here is a "branchless" approach toward that (limited) objective. ("Branchless" coding techniques seek to reduce the impact of "branch prediction misses", an efficiency consideration to reduce processing time.)
Note: the for() loop is only a "test harness" that presents 3 different values for 'y' to be compared to the value of 'x'. The variable 'n' makes more obvious your OP constant '2'. Further, as you are aware, performing multiplication OR division are two completely different operations. This example shows multiplication only. (Replace the '*' with '/' for division with the standard caveat regarding "division by zero" being undefined.) Depending on the probability of "cache misses" and "branch prediction" in modern CPUs, this seemingly complex calculation may require much less processing time than a 'true/false branch' that may bypass processing.
int n = 2; // multiplier
for( int y = 4; y <= 6; y++ ) { // three values for 'y'
int xr = 5; // one value for 'xr'egular
int xb = 5; // same value for 'xb'ranch
(xr == y) ? xr *= n : 1; // to be legitimate C
// when x == y the rhs becomes (n-1)*(1)+1 which equals n
// when x != y the rhs becomes (n-1)*(0)+1 which equals 1 (identity)
// Notice the rhs includes a conditional
// and that the entire statement WILL be evaluated, never bypassed.
xb *= ((n-1)*(xb==y))+1;
printf( "trenaryX = %2d, branchlessX = %2d\n", xr, xb );
}
Output
trenaryX = 5, branchlessX = 5
trenaryX = 10, branchlessX = 10
trenaryX = 5, branchlessX = 5
I hope this makes clear that "trenary" means "3 part" and that this digression into "branchless coding" may have broadened your horizons.
You can use the fact that the result of comparison operators is an int with value 0 or 1...
x == y ? x*=2;
x *= (x == y) + 1; // multiply by either 1 or 2
But a plain if is way more readable
if (x == y) x *= 2;
x == y ? x*=2 : 1;
The syntax requires all three parts... But, if you write code like this, you will lose popularity at the office...
Repeating for those who might have missed it: The syntax requires all three parts.
Actually, you shouldn't do this because as #user229044 commented, "if (x==y) do_something; is exactly what you should do here, not abuse the ternary operator to produce surprising, difficult-to-read code that can only cause problems down the line. You say "I need to know if that's possible", but why? This is exactly what if is for."
As in ternary operator without else in C, you can just have the third/second part of the ternary operator set x to itself, for example, you can just do:
x = (x == y ? x *= 2 : x);
or
x == (y ? x : x /= 2);
I recently started learning C from Sams Teach Yourself C In 21 DAYS, and I can't understand why one expression evaluates to TRUE. It's one of the excersises at the end of the chapter.
x = 4
y = 6
z = 2
if(x != y - z)
I thought that "-" has higher precedence than "!=". What am I missing? I mean, it's getting late and I've been awake since 5am, so maybe my brain is giving up...
The expression in the if statement
if(x != y - z)
may be equivalently rewritten using parentheses like
if(x != ( y - z ))
because the additive operator - has a higher priority than the equality operator !=.
As actually x is equal to the value of the expression y - z then the condition evaluates to the logical false.
So it seems there is a typo in the book.
I have to analyze what some code in C does, and I have a doubt about what happens in a certain line. The code is
#define PRINTX printf("%d\n", x)
void problem() {
int x = 2, y, z;
x *= 3 + 2; PRINTX;
x *= y = z = 4; PRINTX;
x = y == z; PRINTX;
x == (y = z); PRINTX; // This line is the problem
}
This code snippet prints the resulting numbers:
10
40
1
1 // This result **
the problem is that I'm still trying to figure out why does the last line prints out x = 1, when the operation is x == (y = z). I'm having trouble finding out what that 1 means and the precedence of the operations. Hope someone can help me! :)
Nothing in the last statement changes the value of x, so its value remains unchanged.
Parens were used to override precedence, forcing the = to be the operand of the ==.
An operator's operands must necessarily be evaluated before the operator itself, so we know the following:
y is evaluated at some point before the =.
z is evaluated at some point before the =.
x is evaluated at some point before the ==.
= is evaluated at some point before ==.
That's it. All of these are valid orders:
z y = x ==
y z = x ==
x y z = ==
etc.
But whenever x, y and z are evaluated, we can count on the following happening:
= assigns the value of z (currently 4) to y and returns it.
== compares the value of x (currently 1) with the value returned by = (4). Since they're different, == returns 0 (which isn't used by anything).
As you see, nothing changed x, so it still has the value it previously had (1).
In the last statement, nothing is changing the value of x. We are testing if x equals something, but we aren't changing it's value.
So it continues having the same value as it had in the previous statement, in particular, a value of 1.
the reason is because the == operator checks if the 2 numbers are equal, and returns 1 if equal and 0 if not equal that is why it returns one you can check by making x= 1 and y=2 and using the == operator between them
The comparison result of x and assignment of y with (y = z) is discarded. Last line could have dropped the compare: y = z; PRINTX;.
The assignment is not subsequently used either, so the line could have been PRINTX;.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Look at the program-
#include<stdio.h>
int main()
{
int x=2, y=6, z=6;
x = y == z;
printf("%d",x);
}
I thought the output would be 6. I think that z's value is 6 and z is equal to y. So y has the value 6. And the y(which value is 6) is assigned to x. So i think the answer should be 6. But upon execution I find that the the answer is 1. Can anybody explain, why 1 is the output of this program?
x = y == z; is parsed by the compiler as x = (y == z); because of the operator precedence of == is higher than that of = operator.
y == z checks whether y is equal to z or not and produce a Boolean value (either 0 or 1) based on the result of comparison. Since y = 6 = z, y == z returns 1 causing the value of x to be 1. Hence the output is 1.
I think,
You are checking y==z. (y==z) will return a boolean value. So that will be true(1 in C, true in C#). thus the value 1.
Assignment operator works from right to left. so y == z would be first executed. Double equals operator in c checks if both values are same or not. If they are it returns true which is nothing but 1 in c.
This value will then be copied to x. C doesn't have boolean data type it uses integers to store boolean. 1(or any non zero) means true and 0 means false.
if you expected to copy value of z to x, the below line would be more appropriate...
x = y = z; better yet x = z; would also work.
Caveat, it's been a while since I've worked in c.
The initial assignments work as you expect. x=2, y=6, and z=6.
The key is that == is a boolean equals operator. So it basically asks does y equal z? True or false? So your line evaluates in this order:
x = y == z; // Does y equal z? Evaluates to TRUE because 6 equals 6
x = TRUE; // TRUE casts to 1 as an int
x = 1;
#include<stdio.h>
main()
{
int x = 5, y = 10, z = 10;
x = y == z; // This computational expression causes the value of x to be 1. I fail to understand why
printf("%d\n", x); //Why is the value of x 1 here.
}
I fail to understand the statement x = y ==z;
According to me - x = 10 since y == z. z=10 and is stated to be equivalent to y. The value of y is then assigned to x - x = y
You assign the result of the comparison »Is y equal to z« to x, which is 1, i.e. true.
Note the different operators:
x = ... // assignment
y == z // comparison with either 0 (false) or 1 (true) result
Let's break the program down a little bit further:
You initialize x to 5 and y and z to 10.
You perform a comparison (see above) of y and z without caring for the result. So that's a line that can safely be ignored. But it results in 1 since y is equal to z.
You print the current values of all three variables.
You perform the same comparison, this time assigning the result to x. x now has the value »Is y equal to z«, which is 1 in this case.
Because of operators precedence
x = y == z;
is the same as
x = (y == z);
Now as y == z evaluates to 1, so x value is 1 after the statement.
y == z returns 1 if they are the same and 0 if they are not and the result of this is set to x
== is a comparison operator, so will return 1 (true) if both of the operands are equal and 0 (false) if they are not.
The statement x = y == z is equivalent to x = (y == z), because == has a higher precedence than =. Because y is equal to z, this will assign 1 to x.
Please refer to Operator Precedence Table. == (Comparison Operator) has a higher precedence over = (Assignment Operator). So, the y == z gets executed first and then yields result of 1 as y and z are having the same values which results in x being assigned a value of 1.
= is the assignment operator and == is the comparison operator. you compare y and z, they are equal, so the comparison returns true which is 1. this value is assigned to x.
the == operator acts first.
Hence it becomes x= (value of y==z);
now since y and z are the same, the value of y==z is 1 that gets assigned to x.
== has a greater precedence than =.
The expression y == z is evaluated to 1.
The instruction x = y == z puts 1 in x.
The instruction printf("%d\n", x); prints the value of x (1).
The precedence of == operator is higher than = operator.
y==z evaluates to 1; since both are equal.
Thisn value gets assigned to x.