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.
}
Related
Can we write multiple commands like in if statement {between brackets} in conditional operators ?
(For knowledge, not for use)
if (x == 1) {
printf("Printf");
scanf("%d", &scanf);
callFun(calling a function);
}
else if (x == 2) {
printf("Printf2");
scanf("%d", &scanf2);
callFun2(calling a function);
}
int foo(int x)
{
int g,h;
(void)( x == 1 ? ( printf("Hello\n"), scanf("%d", &g), callfunc(g)) : x == 2 ? ( printf("Hello2\n"), scanf("%d", &k), callfunc(h + 5)) : 0);
}
Very easy to read as you see. Better use ifs
This looks clean in my opinion
#include <stdio.h>
void func(){
puts("working");
}
void func1(){
puts("working 2");
}
int main(){
int i = 21;
i == 2122 ? func() : func1();
return 0;
}
This also works
int main(){
int i = 21;
i == 2122 ? (
puts("working 1"),
puts("working 2")
) : (
puts("working 3"),
puts("working 4"));
return 0;
}
The ?: is less generic than if since it requires operands that are expressions. Furthermore it requires both operands to be of the same type. In some cases when they aren't, C implicitly tries to convert them by applying the implicit "usual arithmetic conversions" on the 2nd and 3rd operands. This can lead to unexpected results. For example this code prints gibberish:
printf("%d\n", 1 ? 1 : 1.0);
Even though the 3rd operand is never evaluated, the 2nd operands gets implicitly promoted to double and printing that with %d gives undefined behavior.
To avoid subtle stuff like this, the ?: should be avoided most of the time. It's main purpose in the C language is actually to enable conditions inside function-like macros that return a value. For example we obviously can't write a macro returning a value like this:
#define M(cond) if(cond) { foo(); } else { bar(); }
But it could be done like this:
#define M(cond) ( (cond) ? foo() : bar() )
Similarly, the , comma operator's main purpose is also to enable such macros. So yeah, you could rewrite the code you've written with the ?: in combination with the comma operator. But it's a very bad idea since such code turns unreadable. The only place where it might be justified is inside a function-like macro:
#define M(x) ( x==1 ? (printf("Hello\n"), scanf("%d", &something), callFun(something)) \
: x==2 ? (printf("Hello2\n"), scanf("%d", &something), callFun2(something)) \
: 0 )
This macro would return whatever callFun and callFun2 returns, assuming they return compatible types.
And in case it isn't obvious, function-like macros like these are very bad practice and actual functions are always preferred when possible. Writing macros such as this is should be a last resort, like for example when maintaining some crappy code base where you can't change certain things.
It would be a weird and thus undesireable thing to do, but it can be done.
The key is to use a comma operator instead of separate statements.
(
x == 1 ? (
printf("Printf"),
scanf("%d", &scanf),
callFun(calling a function)
)
: x == 2 ? (
printf("Printf2"),
scanf("%d", &scanf2),
callFun2(calling a function)
)
: (void)0
);
i have conditional operator's statement and i have no idea how its works.
there are two questions:
Question 1 : what will the following statement do :
quotient=(b==0)?0:(a/b) \\ here a,b,quotient is integer
Question 2 : Can preceding statement be written as follow ?
quotient=(b)?(a/b):0;
NOW MY QUESTION IS :
Question:1 :: we do not know b's value then how can we check this condition(b==0)
Question 2:: what (b) indicate ?
The conditional check in the C ternary conditional operator is an implicit comparison to not-zero.
In other words
quotient = b ? a / b: 0;
is the same as
quotient = b != 0 ? a / b : 0;
or the absurd
quotient = (b != 0) != 0 ? a / b : 0;
This is consistent throughout C, e.g. in an if, a for stopping condition, a while, &&, ||, &c.
If you try
int b = 0;
if (b) {
printf("Hello World");
}
Does not print anything while :
int b = 1;
if (b) {
printf("Hello World");
}
Prints Hello World. Why ? Because 0 is false and 1 is true.
If you do quotient=(b)?(a/b):0; it is interpreted to is b true ? or in other words is b evaluated to 1 (while, again, 1 is true and 0 is false)
C did not originally have a Boolean type. Conditionals are simply int values in C. 0 is false, and any other value is truthy. If the type of b is int, or it can implicitly convert to int, then (b) ? foo : bar does the same thing as (b == 0) ? bar : foo. (However, b==0 will evaluate to 1 or 0, whereas b by itself might have other nonzero values that if or ? consider truthy.)
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
can every if...then...else statement be converted into an equivalent statement using only ?:
The code:
if ( flag ) {
exit(1);
}
else {
return 0;
}
cannot be converted into:
flag ? exit(1) : return 0;
A better example - this would be inside a loop:
if ( flag ) {
continue;
}
else {
break;
}
cannot be converted to:
flag ? continue : break;
While any use I can think of for the ternary operator can be implemented as an if/else, the converse is not true; at least not without resorting to perverse and pointless 'tricks' that yield no benefit in terms of performance, readability, or maintainability.
The syntax of if/else is:
if( <boolean expression> )
<statment>|<statment block>
else
<statment>|<statment block>
whereas the syntax of the ?: ternary operator is:
<boolean expression> ? <expression> : <expression> ;
The important thing here being that an <expression> and a <statement> are different syntactic elements.
The very limited usage of the form:
if( b ) x = y else x = z ;
can be implemented as:
x = b ? y : x ;
but here the restriction is that the same variable is being assigned in both the true and false clauses, (and therefore y and z are both at least convertible to the type of x). So it may be said that any conditional assignment can be implemented with the ternary operator (after all that is its primary purpose).
Now since a function call is a valid expression, you could wrap the true and false clauses in separate functions, but to do that simply to prove a point is somewhat perverse:
if( b )
true_stuff() ;
else
false_stuff() ;
is equivalent to:
b ? true_stuff() : false_stuff() ;
and those functions can contain any code at all.
So to convert the more general if/else case to a ?: operation, the true/false statement blocks must first be wrapped in separate functions. However even then Neil Butterworth's examples will defeat this approach since the behaviour of break, continue, and return affect control flow beyond the confines of the if/else construct, (although perhaps those are also examples of code you want to avoid!). The presence of a goto in the if/else would also defeat this approach. .
I think in the end, even if you could, why would you want to?
No.
Both "branches" of the conditional expression must evaluate to the same type, and that type must not be void.
For example, you could do this:
x > 0 ? printf("Positive!\n") : 0;
because printf return int. (I would only use this in a round of code golf, though; in fact, I just did.)
But you cannot do this:
x > 0 ? exit() : 0;
because exit returns void (or, actually, doesn't return at all).