This question already has answers here:
What does the question mark and the colon (?: ternary operator) mean in objective-c?
(13 answers)
Closed 9 years ago.
I heard about a kind of If statement which use ? and : in C
I dont know how to use it and I cant find anything about it.
I need to use it in order to shorten my code
any help would be appreciated.
?: is ternary operator in C (also called conditional operator). You can shorten your code like
if(condition)
expr1;
else
expr2;
to
condition ? expr1 : expr2;
See how it works:
C11: 6.5.15 Conditional operator:
The first operand is evaluated; there is a sequence point between its evaluation and the
evaluation of the second or third operand (whichever is evaluated). The second operand
is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand
(whichever is evaluated),
As others have mentioned, it's called the ternary operator. However, if you didn't know that, it would be somewhat difficult to Google it directly since Google doesn't handle punctuation well. Fortunately, StackOverflow's own search handles punctuation in quotes for exactly this kind of scenario.
This search would yield the answer you were looking for. Alternately, you could search for "question mark and colon in c" on Google, spelling out the name of the punctuation.
First you have the condition before the ?
Then you have the expression for TRUE between ? and :
Then you have the expression for FALSE after :
Something like this:
(1 != 0) ? doThisIfTrue : doThisIfFalse
The ternary operator ?: is a minimize if statement which can reduce this:
if(foo)
exprIfTrue();
else
exprIfFalse();
To this:
(foo) ? exprIfTrue() : exprIfFalse() ;
Personally, I avoid using it because it easily becomes unreadable. The only good example of use is to display the status of a flag in a printf:
int my_flag = 1;
printf("My flag: %s\n", my_flag ? "TRUE" : "FALSE" );
Related
This question already has answers here:
Yet Another Conditional Operator Nesting Question
(2 answers)
Why is the conditional operator right associative?
(3 answers)
To ternary or not to ternary? [closed]
(54 answers)
Closed 5 years ago.
I just got a question idea after having misunderstood a friend's statement.
My friend told me: I just taught a colleague how to do a if/else in one line in c.
Example:
int i = 0;
i < 0 ? printf("i is below 0") : printf("i is over or equal to 0");
For now, nothing new, it's called a ternary and most people know about that kind of statement BUT I first understood that:
I just taught a colleague how to do a IF / ELSE IF / ELSE in one line.
Since I don't / didn't know that doing such a thing is possible I tried to do something like
int i = 0;
i < 0 ? printf("i is below 0") : i == 0 ? printf("i equal 0") : printf("i is over 0");
Is it actually possible to do a if / else if / else "ternary". Or is there a way to do such a thing without having an horrible piece of code?
If you see e.g. this conditional expression reference you can see that the format of a "ternary expression" is
condition ? expression-true : expression-false
All three parts of the conditional expressions are, in turn, expressions. That means you can have almost any kind of expression, including nested conditional (ternary) expressions in them.
It should be noted that conditional expressions might make the code harder to read and understand, especially if used badly or if one attempt to put too much logic and nesting into the expressions.
This is definitely valid.
Or you could try something like this -
printf(i < 0 ? "i is below 0" : i == 0 ? "i equal 0" : "i is over 0");
C has both statements and expressions. There are two different kinds of syntactical things. BTW lines don't matter much in C (except for the preprocessor).
Expressions (like f(1,x+y) or even x=y++) are a special kind of statements (the most common one).
As an extension to C, the GCC compiler adds statement expressions, beyond what the C11 standard (read n1570) defines. Please download then read that n1570 repoort.
if is for conditional statements but the ternary ?: operator is for expressions (with all three operands being sub-expressions).
Some programming languages (notably Lisp, Haskell, Scheme, Ocaml) have only expressions and don't have any statements.
While programming in C, I am using conditional operator (?:). But I don't want to use else part.
if(x!=1){printf("Hello");}
How can I write using conditional operator?
The ternary operator ?: requires an expression if the condition isn't met, you could always place a "dummy" value there such as the value 0 like in the following example:
x != 1 ? printf("Hello") : 0;
An "if" statement would probably be the better way to go in cases like these.
This is a different operator && and it allows you to omit the else part:
#include <stdio.h>
int main () {
int x = 1;
x != 1 && printf ("Hello\n");
return 0;
}
Try running the program, then change x to 2 and run again.
While they appear similar in function, conditional operators are not the same as conditional statements (IF statements).
The main purpose of a conditional operator is to change what value is assigned to a variable, depending on a condition.
Given the following (terrible) example...
if(raining==true)
{
take="umbrella";
}
else if(raining==false)
{
take="sunglasses";
}
That can be rewritten simply as:
take=(raining ? "umbrella" : "sunglasses");
That's the main purpose of a conditional operator. But, as Oliver Charlesworth said in the comments, it is not intended for control flow.
Thus, as a general rule, if you find yourself in a place where you want a conditional operator without the else, you're using conditional operators incorrectly.
I saw lines of C that looked like thi:
rFrameL = block_a.available ?
img->mb_data[block_a.mb_addr].mb_field ?
refPic[list][block_a.pos_y][block_a.pos_x]:
refPic[list][block_a.pos_y][block_a.pos_x] * 2:
-1;
It seems like nested if and else expression but I do not know how it exactly works. is (exp3) returned when (exp1) is true?
is (exp4) returned when (exp2) returned?
is(exp5) returned when (exp1) and (exp2) are false?
With parenthesis around implicit order of operations:
rFrameL = block_a.available ?
(img->mb_data[block_a.mb_addr].mb_field ?
refPic[list][block_a.pos_y][block_a.pos_x]:
refPic[list][block_a.pos_y][block_a.pos_x] * 2):
-1;
Given a?b:c, this means "does a evaluate to true, if yes then evaluate b, otherwise evaluate c". In the above expression, b is being evaluated when a ? is encountered, so it starts a new ternary operation. The first : that is encountered matches up with the second ?, then the second : ends evaluation of b.
This is a nested if-else statement in the ternary operator format.
The '?' refers to 'if' which is solved with the answer in the ':'
In simple, the following code is similar to the ternary operator format :
if (exp1)
{
if(exp2)
{
if(exp3)
{
exp4;
}
exp5;
}
exp6;
}
Is there any method to use a conditional statement inside other statements, for example printf?
One way is using ternary operator ? : eg:
printf("%d", a < b ? a : b);
Is there a method for more complicated conditions?
There is no need for more complex expressions, the conditional operator is already bad enough. There is no language feature for it. Instead, write a function.
printf("%d", compare(a,b)); // good programming, readable code
printf("%d", a<b?(x<y?x:y):(x<y?y:x)); // bad programming, unreadable mess
Every conditional statement return 1 or 0. These values are int
So if you do printf("%d",a>b); then either 1(true) or 0(false) will be printed.
In your example you are using ternary operator a<b?a:b.
If condition is true then a will be printed else b.
You cannot put statements into printf at all, you only can put expressions there. The ternary operator forms an expression. An expression is basically a tree of operators and operands, however there are a few funny operators allowed, like the ',' comma operator or the '=' assignment operator. This allows expressions to have side effects.
the following c statement is not passing through compiler .error being "expected expression before return".
int max( int a,int b)
{
a>b?return a:return b;
}
and yeah ,i know i can write this for finding max as
return a>b?a: b;
which is quite okay and will run perfectly.
but my question is what is exact problem with the first code.why cant we use return in ternary opoerator,although we can use function call quite easily over there?
THANKS in advance!!!
The C grammar says that the things after the '?' and the ':' must be expressions - return is not an expression, it is a statement.
The operands of ternary ?: are expressions. A return statement is a statement, not an expression.
?: is an operator not a control flow construct, so the whole thing with operands must be an expression, and return statements (or any statement) are not valid sub-expressions.
?: is not simply a shorthand for if-else (which is a control flow construct); it is semantically different.
if( a > b ) return a; else return b;
on the other hand is what you were trying to do, and entirely valid (if perhaps ill-advised stylistically).
The second and third parts of the ternary expression are expected to yield values, not be return statements as in your example.
Ternary operator needs expression,return is a statement.
More about conditional operator here.