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

Asked

Viewed 2,858 times

11

When I should 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 is not very clear to me how the conditions are validated. Its structure would be:

variavel = decisão ? valor_verdadeiro : valor_falso

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

1 answer

19


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

He is also called ternary operator, but I don’t like the term. If one day you have another ternary, it creates confusion, and this name doesn’t say what it does, it’s bad terminology.

In a way he’s a substitute for the if, at least when you just want to take a value according to the decision. Obviously it cannot execute commands, it can only execute expressions. And if it gets too complicated, even though it still works, it becomes unreadable, especially if it has several nested conditions.

So use only when it 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’s too much, it’s 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 trouble precedence.

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

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

I put in the Github for future reference.

Assuming that the variable is already declared, because if it is first use, and usually would be, then there would still be a line with the conditional operator and would have an extra line in the form of the if.

See more in another answer, the language is different but works the same. There’s this one too.

  • Thank you very much for the explanation. Really without relatives it confuses and becomes difficult to read, I will try to use it more carefully and only in specific cases.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.