I am looking to write conditional code without using (if/else/?/while etc...) in C language.
For example the following code:
if (Num>6) printf("T");
can be converted to (And still do the same task):
Num>6 && printf("T")
but the following:
bool larger;
if (Num>6) larger=true;
can't be replaced with:
bool larger;
Num>6 && larger=true;
Since lvalue is required as left operand of assignment
Any help? (I think && operation and the use of bool would be helpful)
Add parentheses around:
bool larger;
Num > 6 && (larger = true);
Why? Because = has lower precedence than && and >. That means the expression is parsed as
((Num > 6) && larger) = true;
which is an invalid assignment
Demo on compiler explorer
Related
Conditional operator in C is used like this:
condition ? value_if_true : value_if_false
What does 0 mean when it's used in the value_if_false?
I've seen some people using it like this, for example.
a == b ? i++ : 0
It seems like it does nothing. Does this work like return 0 in other functions?
In C language, ternary is shorter version of if statement and it requires both statements, if_true and if_false. It would be like this (in fact it can have multiple statements for one case, separated with comma):
Short:
condition ? if_true : if_false;
Long:
if (condition) {
if_true;
} else {
if_false;
}
You can also assign the value if you put something infront of condition.
Short:
result = condition ? if_true : if_false;
Long:
if (condition) {
result = if_true;
} else {
result = if_false;
}
Now here is the trick. In C language, writing 0; is a valid statement, so your ternary becomes in longer version same as code below:
if (a == b) {
i++;
} else {
0; /* This is valid C statement */
}
Or if you have assignment too, it would be:
if (a == b) {
result = i++;
} else {
result = 0;
}
You can also do this:
int a;
/* Code here ... */
condition ? a = 5: 0;
That is effectively the same as:
if (condition) {
a = 5;
} else {
/* DO not touch a */
}
The ?: operator is a ternary operator, but it is not called "ternary" as some answers and/or comments here suggest. It just is the arity of the operator, just as + is a binary operator or as & is unary. If it has a name at all, it is called "Conditional Expression"-operator
It is not quite equivalent to if/else, because it is a conditional value (with the consequence, that both expressions must have the same type) in the first place, not a conditional execution. Of course, both types can be cast to make them equal.
In the case of what the OP does, a better option (if if shall not be used) is in my opinion:
a == b && i++;
which resembles a bit more logical what happens. But of course it is a matter of style.
The reason why someone might want to write a == b ? i++ : 0; is that s/he probably wants to have an (Caution! You are now entering an opinion-based area) easier and faster alternative to if (a == b) i++; - although this is of course opinion-based and I personally not share the same opinion.
One thing I can think of as a "blocker" at the if statement is the requirement to write the parentheses () which can be omitted by using the conditional operator instead.
"But why the 0?"
The C syntax requires a third operand for the conditional operator. Else if you would want to compile for example:
a == b ? i++;
you will get an error from the compiler:
"error: expected ':' before ';' token"
Or respectively, doing so:
a == b ? i++ : ;
would raise:
"error: expected expression before ';' token"
So they use 0 as kind of "syntax satisfier" to be able to use the conditional operator as replacement for the if statement. You could use any other numeral value here as well, but 0 is the most readable value, which signifies that it has no use otherwise.
To showcase the use at an example:
#include <stdio.h>
int main (void)
{
int a, b, c = 4;
a = 2;
b = 2;
a == b ? c++ : 0;
printf("%d",c);
return 0;
}
The output for c will be 5, because a == b.
Note that a == b ? i++ : 0 is different when used f.e. inside of an assignment like f.e.:
int c = a == b ? i++ : 0;
Here c is either getting assigned by i or 0, dependent upon a == b is true or not. If a == b is true, c is assigned by i. If a == b is wrong, c is assigned by 0.
Side Notes:
To view it from a technical point, ?= is called the "conditional operator". The conditional operator is one of the group of ternary operators.
If you want to learn more about the conditional operator ?=, look at ISO:IEC 9899:2018 (C18), §6.5.15 - "Conditional operator" for more information.
There's nothing special about 0 one could write
a == b ? i++ : 1
And it would behave the same way.
Only difference is when you assign the expression to say another variable:
int c = a == b ? i++ : 1;
// a == b -> c will be i++
// a != b -> c will be 1
However it's much cleaner to write
if (a == b) i++;
It helps to think of the ternary operator as a shorthand way or writing an if-else statement.
If(a == b){
i++;
}else{
//if assigned, return 0. Else do nothing.
}
#include<stdio.h>
int hailstone(int n){
int length=1;
while(1<n){(n%2)?n=3*n+1:n/=2;length++;}//error
//while(1<n){(n%2)?n=3*n+1:(n/=2);length++;} right
return length;
}
int main()
{
int n;
scanf("%d",&n);
printf("%d\n",hailstone(n));
}
There is an error in line four,the gcc compiler said lvalue required as left operand of assignment,but if i add brackets it will be right.like line five,and i don not know why.
Despite shoving all the logic into one line, the problem is actually in one expression (pardon me for adding spaces):
(n%2) ? n=3*n+1 : n/=2
The precedence rules for C expressions are like that. Assignment (and that includes compound assignment) binds less tightly than ?:. So the compiler has to interpret what you wrote as:
((n%2) ? n=3*n+1 : n) /=2
Since ?: doesn't produce an lvalue (something that can appear on the left of an assignment), you get an error. Your use of parentheses forces the precedence to match what you wanted.
But an even better way to write that is to not be "clever" and think there is some "elegance" in using as much tokens as possible in a single expression. Here's another version, which is far more readable, and easier to verify as correct:
if (n%2) {
n = 3*n+1;
} else {
n /= 2;
}
And it's no less efficient than using a conditional expression.
Here the compiler takes l value as
((n%2) ? n=3*n+1 : n) /
and r value as
2
Since ((n%2) ? n=3*n+1 : n) / = 2 is an invalid statement and l value is not a variable, compiler throws error. You can provide the precedence of execution to the compiler by adding brackets.
#include<stdio.h>
main()
{
int big,x=3,y=2,z=1,q=4;
big=( x>y ? (x<z ? 20:10 && y>x ? 50:10 ) : (y>z ? 40:10 || x<q ? 30:10));
printf("big =%d",big);
return 0;
}
&& is a relational operator so it should return a true or false value i.e 0 or 1, but in this case its not. Please explain whats the logic behind its output?
Output: big =10
It's all about operator precedence (and a distressing lack of parentheses).
The output I get when I run your program is nbig =10 (with no newline; you should add a \n to your format string).
The value assigned to big isn't the result of an && or || operator. Let's reduce that over-complicated expression, one step at a time. (I've confirmed at each step that the result is unchanged.)
big=(x>y?(x<z?20:10 && y>x?50:10) : (y>z?40:10 || x<q?30:10));
We know that x>y is true, so we can drop the test and the third operand of the corresponding ?: operator:
big=(x<z?20:10 && y>x?50:10);
Let's remove the extraneous outer parentheses, add some new around the third operand of the outer ?: operator, and change the spacing a bit:
big = x<z ? 20 : (10 && y>x?50:10);
We know that x<z is false, so we can drop that and the second operand of the outer ?::
big = (10 && y>x?50:10);
Obviously 10 is true, so:
big = (y > x ? 50 : 10);
And y > x is false, so the result is 10 -- which is what I get when I run your program.
You probably assumed that this:
a ? b : c && d ? e : f
is equivalent to:
(a ? b : c) && (d ? e : f)
but in fact it's equivalent to:
a ? b : ((c && d) ? e : f)
because the && operator binds more tightly than the ?: operator.
In any case, if this is real code, you should definitely add enough parentheses so that a reasonably knowledgeable reader can understand the code without having to consult an operator precedence table. Mixing &&, ||, and ?: can be particularly confusing. Breaking down the expression into subexpressions, and assigning each one to a temporary variable (so it has a meaningful name) can also be helpful.
The above applies if you're trying to write a complex expression. If you're trying to understand something that someone else has written, you pretty much have to parse it yourself. Try doing what I did: incrementally simplify the expression (by removing parts or adding parentheses) in ways that don't change the meaning, confirming at each step that you get the same result. And if it's production code (rather than a quiz, which this appears to be), consider complaining bitterly encouraging the author to write clearer code.
Let's make your expression a bit more explicit by adding parethesis to show the precedence:
((x>y) ?
((x<z) ?
20 : ((10 && (y>x)) ? 50 : 10)
) : (
(y>z)?40:((10 || (x<q))?30:10)
)
)
x is greater than y, so let's consider
((x<z) ?
20 : ((10 && (y>x)) ? 50 : 10)
)
and x is not less than z, so
((10 && (y>x)) ? 50 : 10)
y is not greater than x, so
10
You can see that the results are not actually of your logical operators. Because of the complexity involved, you should almost certainly express such an evaluation using if statements to break up the logic in a clean way.
This question already has answers here:
What does the question mark character ('?') mean?
(8 answers)
Closed 10 years ago.
K&R Second Edition (page 71)-- I must have missed the explanation:
sign = (s[i] == '-') ? -1 : 1;
The context of this is a function that converts a string to a double. This part in particular comes after the function skips white space. I infer it is checking for positive or negative value, and saving it as either -1 or +1 for sign conversion at the end of the function... return sign * val /power;
I would like to do better than infer... I'm particularly unsure of what the ? and : 1 are doing here (or anywhere, for that matter).
It kind of seems like an abstract if statement. Where ? checks for truth and : is else... is that so? Is it limited to if/else?
I am a beginner and I haven't come across this expression syntax before, so I am wondering if there is a particular reason it seems to often be replaced by a formal if/else--besides, perhaps, readability?
It kind of seems like an abstract if statement, where ? checks for truth and : is else... is that so?
Yeah, almost. It's called the "conditional operator" (sometimes not entirely accurately referred to as "the ternary operator", since it's the only ternary operator in C). It's not a statement though, it's an expression, it has a value. It evaluates to its second argument if the first argument evaluates to true, and to its third argument if it's false. Therefore
sign = (s[i] == '-') ? -1 : 1;
is equivalent to
if (s[i] == '-') {
sign = -1;
} else {
sign = 1;
}
It kind of seems like an abstract if statement.
That's correct. This is called a "ternary conditional operator".
The normal if works on statements, while the conditional operator works on expressions.
I am wondering if there is a particular reason it seems to often be replaced by a formal if/else--besides, perhaps, readability?
There are cases where branching on statements is not enough, and you need to work on the expression level.
For instance, consider initialization:
const int foo = bar ? 5 : 3;
This could not be written using a normal if/else.
Anyway, people who are saying it's equivalent to the if/else are being imprecise. While the generated assembly is usually the same, they are not equivalent and it should not be seen as a shorthand version of if. Simply put, use if whenever possible, and only use the conditional operator when you need to branch on expressions.
This is the ternary operator. (s[i] == '-') ? -1 : 1; returns -1 if s[i] == '-' and 1 otherwise. This value is then assigned to sign. In other words, a longer way to write this would be:
int sign;
if(s[i] == '-')
{
sign = -1;
}
else
{
sign = 1;
}
?: is the conditional operator in C.
In your example it would produce the same result as this if statement:
if (s[i] == '-')
{
sign = -1;
}
else
{
sign = 1;
}
sign = (s[i] == '-') ? -1 : 1;
is shorthand for:
if (s[i] == '-')
{
sign = -1;
}
else
{
sign = 1;
}
For learning purposes, I wrote the following code snippet:
for(int i=0;i<10;i++)
{
for(int j = 0;j<5;j++)
{
//(i==j && i==3)? (goto found) : printf("stya here\n");
if(i==j && i==3){goto found;} else {printf("stay here\n");}
}
}
found:
printf("yes I am here");
But I wondered when I discovered the omitted statement inside the inner loop not gives error and now I am confused about if-else is not always replaceable with ?: operator. What is the fact here? Why does the commented statement give an error?
The ?: operator is not replacement for if. It works only for expressions: condition ? expr1 : expr2 where both sub-expressions expr1 and expr2 are of the same type (and the whole expression then is of the same type).
goto is not expression, it is a statement.
I am not well versed enough in C to explain why this doesn't work syntactically, but in the sense of intent the ?: ternary operator form is intended as a conditional expression (yields a result), not as a control flow mechanism. Using the if statement you can choose a value for a variable or change the flow of the application.
e.g.
//Change flow
if(x ==0)
{
//do this
}
else
{
//goto some label
}
or
//Change value
if(x == 0)
{
y = 1;
}
else
{
y = 2;
}
The ternary is only intended for the second case, as a conditional expression
i.e.
y = (x ==0) ? 1 :2;
Actually, what you're trying to do with goto and the ternary operator is possible if your compiler support the extension Statement Expressions, as it's name said, this extension allow you to write statements inside an expression or sub-expressions, just like this:
(rand() % 2) ? ({goto lbl1;}) : ({goto lbl2;});
Using these statements can be very useful (mostly to optimize macros) but often lead to very dirty code, just like the example i gave :)
So to complement the other answers i'll say that it's not possible in C99/11 without extension but most of the recent compiler support a bunch of extension that allows you to do non-standard cool things.
What would be the result of "goto found" expression? I don't know, neither does the compiler, so the result of ? expression cannot be determined, hence the error.
In general, the ?: operator is no replacement for a classic if() ... else() .... It might be used as such if both operators (and the condition) are values or expressions returning a value. You can't use them with statements like goto, break or continue.
The following would be possible:
condition ? dothis() : dothat(); // there's no assignment, but it's still valid
var = condition ? dothis() : othervar;
condition ? (var=4, othervar=3) : (somevar = 1);
But you can't include anything that's not an expression (i.e. nothing not having some value or result):
condition ? continue : break; // statements letting the execution continue somewhere else
condition ? {var = 4; othervar = 3;} : dothat(); // trying to inline scopes/multiple exressions
var = condition ? while(var) {var--;} : 5; // similar, inlining a complete loop
These last examples can be done, but they'd require you to use if() or function bodys to call:
if (condition) continue; else break;
condition ? (var = 4, var = 3) : dothat();
var = condition ? dotheloop(var) : 5; // ok, this could be 'var = condition ? 0 : 5;' but... example code