Thread: error when using ?:

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    3

    error when using ?:

    Hi Everyone,
    I'm getting the error Lvalue required when I'm compiling the following program

    Code:
    #include <stdio.h>
    
    int main()
    {
    int a=1,b,c;
    clrscr();
    c=(a>5)?b=5:b=4;  /* here it is giving the error */
    printf("c=%d\tb=%d\n",c,b);
    getch();
    return 0;
    }
    When i changed the line to the following it is runnig fine.

    Code:
    c=(a>5)?b=5:(b=4);
    can anyone explain to me what is the reason for the error in the first case.

    Regards,

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    So are you trying to set both b and c to the same value?
    Code:
    c = b = a > 5 ? 5 : 4;
    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    Still the code seems correct...
    c = (condition)?expression:expressiom;

    I think the compiler is grouping symbols like this
    c=(a>5)?b=5:b=4;
    c=expression=4;
    but it shouldn't
    http://www.cppreference.com/operator_precedence.html
    Last edited by xErath; 05-20-2005 at 12:42 AM.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Actually yes, that's what it is doing, and it should. The ? : is resolved right to left, before the = is.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed