Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

trying three numbers comparision with ternary operator does not work

#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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

?: 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 =.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading