Ternary operator in C language

ternary operator

form:

A ? B : C

It is equivalent to

if(A)
    B;
else
    C;

example:

#include <stdio.h>
int main()
{
    
    
    int i;
    i = (3>2 ? 5 : 1);
    printf("i = %d\n",i);
    return 0;
}

The output is: i = 5

The code for this example is equivalent to:

#include <stdio.h>
int main()
{
    
    
    int i;
    if(3>2)
    {
    
    
        i = 5;
    }
    else
    {
    
    
        i = 1;
    }
    printf("i = %d\n",i);
    return 0;
}

Although the ternary operator does seem to have less code, I personally feel that it is easier to read the code using the if statement.

Supongo que te gusta

Origin blog.csdn.net/YuanApple/article/details/129760310
Recomendado
Clasificación