When should I use the "?" operator in C?

8

When should I use the ternary operator ? in C?

#include <stdio.h>

int main(void)
{
    int valor, resultado;

    printf("\nValor: ");
    scanf("%d", &valor);

    resultado = valor < 10 ? 50 : 0;

    printf("\nResultado = %d", resultado);

    return 0;
}

It's not very clear to me how validated the conditions are. His structure would be:

variavel = decisão ? valor_verdadeiro : valor_falso

I also have doubts about : , is it also an operator? Or is it only used in conjunction with ? ?

    
asked by anonymous 13.10.2015 / 19:20

1 answer

12

The conditional operator is ? : . They are not two operators. Since it is ternary, it has two parts to separate, as you well observed, the condition, the value for true, and the value for false.

It's also called the ternary operator , but I do not like the term. If one day has another ternary, it causes confusion. And this name does not say what it does. It's bad terminology.

In a way it is a substitute for if , at least when you just want to get a value according to the decision. Obviously it can not execute commands, it can only execute expressions. And if it gets too complicated, though it still works, it's unreadable. Especially if you have multiple conditions nested.

So use only when fits a simple expression and will not nest. It is common to use parentheses in the condition even when it is not necessary. Other times parentheses are used throughout the operator expression:

resultado = ((valor < 10) ? 50 : 0);

Of course in this case it is exaggeration, it is simple enough not to cause confusion. But if this expression were part of another expression, it would be more confusing without parentheses. And obviously in some cases it becomes mandatory to achieve what you want without having problems precedence .

I prefer this in simple cases, but you have to do it:

if (valor < 10)
    resultado = 50;
else
    resultado = 0;

See more in another answer . Language is different but works the same. There is this too .

    
13.10.2015 / 19:30