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).
Related
while(1) {
// other stuff
// there's no code in the loop after the below statement:
count>=10? break : continue; // error
}
Why does this statement give errors? Any help will be highly appreciated.
58 16 [Error] expected expression before 'break'
This is the error that the compiler gives.
Why does this statement give errors ?
?: is not a "short version of if" as it is incorrectly described on many sites.
?: is not a statement, it is an operator.
An operator joins one, two or three operands to produce an expression. An expression is a piece of code that is computed and produces a value. A statement is a piece of code that does something. They are different things.
A statement can contain expressions. An expression cannot contain statements.
break and continue are statements. This is why the fragment count >= 10 ? break : continue; is not a valid statement and does not compile.
Use an if statement and it works:
if (count >= 10) {
break;
} else {
continue;
}
As it follows from the error message
58 16 [Error] expected expression before 'break'
in this statement with the conditional operator
count>=10? break : continue;
the compiler expects expressions instead of the statements break and continue.
According to the C Standard the conditional operator is defined the following way
logical-OR-expression ? expression : conditional-expression
As you can see it includes three expressions.
Instead of using the conditional operator you could use the if-else statement the following way
if ( count>=10 )
{
break;
}
else
{
continue;
}
But in any case this construction with break and continue statements looks badly.
It seems you should move the condition count>=10 in the loop statement that is used. Or it will be enough to write
if ( count>=10 )
{
break;
}
without the else part of the if statement.
Conditional operator:
a ? b : c - if a is logically true (does not evaluate to zero) then evaluate expression b, otherwise evaluate expression c
Neither break nor continue are expressions. They are statements and can't be used with the conditional operator.
Furthermore, continue as the last statement in your loop is pointless.
What you need is simply:
while(1) {
// other stuff
if(count >= 10) break;
}
or even simpler:
do {
// other stuff
} while(count < 10);
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.
}
Can someone please explain me the working of Nested If-Else Statements written WITHOUT the Curly Braces.
I want to understand why Below Programme isn't giving me any output.
I've checked for all the 4 possibilities.
(Outer-If, Inner-If)::(True, True),(True, False),(False, True),(False, False).
I'm editing with CodeBlocks,using gcc compiler on Windows.
int main()
{
int n=0,m=0;
if ( n > 0 )
if ( m > 0 )
printf("Inner-If Condition satisfied.");
else
printf("Inner-If condition not satisfied. ");
return 0;
}
Thank You.
They work as-if there was a curly brace around the following statement. In your case then:
if ( n = 0 ){ // ToDo - did you mean `==`, `n = 0` is `0`.
if ( m = 0 ){ // ToDo - ditto.
printf("True");
} else {
printf("False");
}
}
In your case I think the bewilderment stems from your using = rather than ==.
The if-else ambiguity is solved by defining that an ambiguous else belongs to the nearest if.
The parser will see an ambiguity, however, the parser has ben adapted to solve the ambiguity as described above (e.g. yacc).
Note: the reason your program does not give any output is because n=0 (an assignment) results in n being zero and so the test becomes false, so the branch is not taken and the return is executed.
n = 0 is an assignment in C. It assigns n the value 0. Assignments also evaluate to the value that is assigned, so here, to 0, which is in a boolean context false -- so your outer if is always false.
To compare two values, use == instead, which evaluates to 1 (true) on equality, 0 (false) on inequality. *)
Your assumption about if and else was correct, the reason you don't see output is just your wrong attempt at comparing values.
A good compiler will warn you of such typos. E.g. with gcc, enable a reasonable set of warnings with -std=c11 -Wall -Wextra.
*) as a side note, in a boolean context, a zero value is false and any other value is true, so you could also write the code like this (! is logical not, inverting true and false):
if (!n)
if (!m)
// ...
Whether this is good style depends on who you ask. I personally like to write it this way if 0 semantically represents the lack of a value, or if the variable is already meant as a boolean value. Then "if not n" sounds kind of natural.
Use == inside if Statement. such as below mentioned code will work.
if ( n == 0 )
if ( m == 0 )
printf("True");
else printf("False");
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.
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