Conditional statements inside `printf` - c

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.

Related

Why break cannot be used with ternary operator?

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.

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.

If statement with ? and : [duplicate]

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

Does C have a concatenation operator?

This Verilog tutorial (see the table at the end) suggests that { } is a concatenation operator is C. I don't remember curly brackets as being an operator in C.
Is { } a concatenation operator in C?
No, that's just nonsense. No idea what that's about.
From the linked tutorial:
To make life easier for us, nearly all operators (at least the ones in the list below) are exactly the same as their counterparts in the C programming language.
Emphasis mine. The exceptions are ~&, ~|, ~^, ^~, and {}.
Adjacent string literals are automatically concatenated:
char *str = "This is the first half "
"and this is the second half";
Anything involving a char buffer, though, requires a library function like strcat:
char buf[SOME_SIZE];
...
strcat(buf, "This is the first half ");
strcat(buf, "and this is the second half");
There is also the preprocessor token pasting operator ##, but the result must be a valid preprocessor token.
Absolutely not. The curly braces in C as C++, C# and others delimit a block of code. It's an error on their site. There is neither the possibility of operator overloading since we talk of 'pure, old fashioned C programming language'
The only operator C has with { } is the ( ){ } operator which is the compound literal operator.
No, in pure C, the braces are not a concatenation operator.
Note that the table of operators on the Verilog page includes a number of other 'non-C, non-C++' operators:
~& nand
| or
~| nor
^ xor
^~ xnor
~^ xnor
Where the operators are the same as in C, they have the same meaning as in C. But there are operators in Verilog that are not in C (and, if that table is complete, operators in C that are not in Verilog).
Depends. Curly brackets are not an operator by definition in C, and they do not concatenate strings. But they group statements and introduce new blocks. Maybe this is what the author meant. But however, it is at least inaccurate if not wrong.
## is a concatenation operator....

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