IF short syntax in c

95,938

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

printf(arraeck(a,n) ? "YES" : "NO");
Share:
95,938
Blondy21
Author by

Blondy21

Updated on January 09, 2020

Comments

  • Blondy21
    Blondy21 over 4 years

    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 ?