i know that if can be writen in short way syntax in c please show me how
if arraeck(a, n) ? printf("YES") printf("NO");
some thing like this?..in one line... What is the correct syntax ?
The short answer here is that you've written illegible code that you can no longer read. A few things to consider: (1) Use more, smaller, well-named functions (2) Use meaningful variable names (3) Make if statements that read like english.
Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy.
Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of code to be executed.
The syntax of an if...else statement in C programming language is − if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
?:
is not equivalent to if
: the latter is a statement, but the former is an expression.
You can do:
arraeck(a, n) ? printf("YES") : printf("NO");
but it is bad style.
You can also do
str = arraeck(a, n) ? "YES" : "NO";
printf(arraeck(a, n) ? "YES" : "NO");
but you can't write
str = if (arraeck(a, n)) "YES"; else "NO";
printf(if (arraeck(a, n)) "YES"; else "NO");
if (cond) {
exp1;
} else {
exp2;
}
Can be written as
cond ? exp1 : exp2;
This form is commonly used for conditional assignment like this (from Wikipedia entry of ?:):
variable = condition ? value_if_true : value_if_false
Direct translation of your sample code:
arraeck(a, n) ? printf("YES") : printf("NO");
Or even shorter:
printf(arraeck(a, n) ? "YES" : "NO");
This is called the (ternary) conditional operator ?:
and it's not always the best solution to use it, as it can be hard to read. You usually only use it if you need the result of the conditional, like in the second code sample (the operator evaluates to "YES"
or "NO"
here).
In the first sample, the operator is not used as an an expression, so you should better use an explicit if
(it's not that long after all):
if (arraeck(a, n))
printf("YES");
else
printf("NO");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With