Conditional operator?: is not working

1

I can not use 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;
 }
    
asked by anonymous 04.02.2018 / 00:27

2 answers

4

The conditional operator only accepts expressions and not statements , so it does not work. Both can be best written using conditional operator only in 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);
}
    
04.02.2018 / 00:34
1

Use the normal if else

if(num1 < num2)
    resposta = 10;
else
    resposta = -10;
    
04.02.2018 / 00:31