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;
}
Related
while(*p!='\0' && *q!='\0')
{
if(*p==*q)
{
p++;
q++;
c++;
}
else
break;
}
I have written this using ternary operator but why its giving error for break statement?
*p==*q?p++,q++,c++:break;
gcc compiler gives this error: expected expression before ‘break’
When you use a ternary operator, it is not like an if. The ternary operator has this form:
(condition ? expression_if_true : expression_if_false);
Those two expression must have the same type, otherwise that makes nonsense.
And as Thilo said, you cannot use statement in this operator, only expression. This is because the whole ternary operator must be an expression itself, depending on the condition.
The syntax is:
(condition ? expr_true : expr_false);
expr_true and expr_false must have a common type (which will be the result of the ternary operator).
Also, of course, break is not an expression, it is a statement.
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.
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" );
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
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.