How to write a conditional operator (?:) without using else - c

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.

Related

Is it possible to use continue in conditional operator? in c language

I am going to print no if for loop i is not divided by 3 and otherwise continue the loop
(i%3==0)? continue : (printf("no"));
am getting error on this line
No. In a ternary operator, both of the values must be expressions. continue is a statement, not an expression. Use an if statement instead.
I would say you can do it with while loop easily :
while(1){
if(i%3 == 0)
i = i % 3;
}else{
printf_s("no");
break;
}
This will not work as the conditional operator is part of an expression whose value is either the second or third clause, and continue is a statement.
The conditional operator can be used in ways such as this:
days_in_february = is_leap_year() ? 29 : 28;
So now imagine if what you wanted was allowed. If you did this:
val = (i%3==0)? continue : (printf("no"));
Then what would value be set to if the condition was true? continue is not an expression and therefore doesn't "have a value" so such a statement wouldn't make sense.
You need to use a standard if statement to accomplish this:
if (i%3==0) {
continue;
} else {
printf("no");
}

Conditional statements inside `printf`

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.

goto not working with ?: operator in C

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

Conditional operator in C

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).

expected expression before return

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.

Resources