Conditional operator ?: not working

Asked

Viewed 70 times

0

I’m having trouble using the ?:

 #include <stdio.h>

 int main()
 {
 int num1 = 10;
 int num2 = 20;
 int resposta;

 num1 < num2 ? printf("sim\n") : printf("nao\n");

 // O erro acontece aqui ao compilar

 num1 < num2 ? resposta = 10 : resposta = -10;

 printf("%i\n", resposta);


 return 0;
 }
  • The ternary accepts statements when inside (): num1 < num2 ? (resposta = 10) : (resposta = -10);, but as in your case is to make a value assignment, the answer below is the best solution.

2 answers

4


Conditional operator accepts only expressions and does not statements, so it doesn’t work. Both can best be written using conditional operator only at the part that actually varies, and that is an expression.

#include <stdio.h>

int main() {
    int num1 = 10;
    int num2 = 20;
    printf(num1 < num2 ? "sim\n" : "nao\n");
    int resposta = num1 < num2 ? 10 : -10;
    printf("%i\n", resposta);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I noticed that your algorithm is shorter than mine, I still do not know what can and can not, for example did not know that could use this operator "?:" within a "printf", or even on the same line as the variable statement line. suggests me some book or something to kind so I can deepen my knowledge?

  • 1

    @Gabrieldasilvasantos probably because he’s learning the wrong way, like almost everyone else. The suggestion is to learn the basics before learning to program. I don’t like to suggest anything because everything is not always good, not always good for the person, not always the person will know how to use it properly.

0

Use normal if Else

if(num1 < num2)
    resposta = 10;
else
    resposta = -10;
  • Your solution is good, but I would like to know how to use the operator " ?: "Because, is what I was breaking my head.

  • Hi Antony! It is always good to join text to explain code, so it is clearer to everyone how the code works

  • Okay, Gabriel. I get Sergio. I joined the community now, I’m still learning how to behave here. Thanks for the tip!

Browser other questions tagged

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