Why break cannot be used with ternary operator? - c

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.

Related

count>=10? break : continue;

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

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

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.

C: What does (exp1)? (exp2)? (exp3) : (exp4) : (exp5) operator do?

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;
}

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.

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