Search code examples
carraysternary-operatorlvalue

i % 2 == 0 ? arr[i] = 0 : arr[i] = 1; Ternary operator error


About ternary operator. I was rewriting an if-else statement in C, using the more clean ternary operator. Here´s the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int arr[10];
    int i;

//    for ( i = 0; i < 10; i++ )
//    {
//        if ( i % 2 == 0 )
//        {
//            arr[i] = 0;
//        }
//
//        else arr[i] = 1;
//    }

    for ( i = 0; i < 10; i++ )
    {
         i % 2 == 0 ? arr[i] = 0 : arr[i] = 1;//Line in question
    }

    /* Just to check the result */
    for ( i = 0; i < 10; i++ )
    {
        printf ( "%d ", arr[i] );
    }

    return 0;
}

The commented code did work but for my surprise, when I compiled the file with the ternary operator, I got the following:

C:\Users...\main.c|21|error: lvalue required as left operand of assignment|

This is a simple code to check weather the position in the array is odd or even. Did a search and the only thing that I read that is related with this code is that the lvalue is a variable. If that is true I´m going to refer an example that to this day I haven't got an answer for:

printf ( "%d", 23 + 4 );

The placeholder is going to be replaced by the literal value of 27. No variable is involved here, it works tough. Thank you.


Solution

  • Change:

    i % 2 == 0 ? arr[i] = 0 : arr[i] = 1;
    

    to this:

    i % 2 == 0 ? (arr[i] = 0) : (arr[i] = 1);
    

    The conditional operator has higher precedence than the assignment operator.

    As suggested in the comments, you can get the same result with:

    arr[i] = (i % 2 == 0 ? 0 : 1);
    

    or simply:

    arr[i] = i % 2;