Home > Net >  trying three numbers comparision with ternary operator does not work
trying three numbers comparision with ternary operator does not work

Time:04-20

#include <stdio.h>

void main()
{
    int n1, n2, n3, l;

    printf("Enter any three numbers:\n");
    scanf("%d %d %d", &n1, &n2, &n3);

    (n1 >= n2) ? l = n1 : ((n1 >= n3) ? l = n1 : ((n2 >= n3) ? l = n2 : l = n3));

    printf("Largest number = %d", l);
}

says "lvalue required as left operandof assignment"

edited:

#include <stdio.h>

void main()
{
    int n1, n2, n3, lar;

    printf("Enter any three numbers:\n");
    scanf("%d %d %d", &n1, &n2, &n3);

    lar = n1 >= n2 ? n1 : n2;
    lar = lar >= n3 ? lar : n3;

    printf("Largest number = %d", lar);
}

this one works except had to break down to 2 parts

CodePudding user response:

?: has higher precedence than =. You should do:

better_name_than_l = (n1 >= n2) ? n1 : ((n1 >= n3) ? n1 : ((n2 >= n3) ? n2 : n3))

As a bonus, the code went from "very unreadable mess" to just "slightly unreadable mess".

l (L) is an incredibly bad name for a variable, since it looks like 1 (one) on many fonts - to the point where safety standards like MISRA C have explicitly banned l as a variable name.

Also, since we've already established that we hate readable code (this is for code golfing, right?) we can even drop the inner parenthesis everywhere:

better_name_than_l = n1 >= n2 ? n1 : n1 >= n3 ? n1 : n2 >= n3 ? n2 : n3;

Precedence is >= over ?: over =.

  • Related