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

On the ternary operator. I have rewritten the if-else statement in C using a cleaner ternary operator. Here is 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 to my surprise, when I compiled the file with the ternary operator, I got this:

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

This is a simple code to check the weather, the position in the array is odd or even. Was there a search and the only thing I read related to this code is that lvalue is a variable. If this is true, I will give an example that has not received an answer to this day:

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

      

The placeholder will be replaced with the literal value 27. There is no variable here, it works hard. Thank.

+3


source to share


4 answers


Edit:

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

      

:

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

      

The conditional operator takes precedence over the assignment operator.



As pointed out in the comments, you can get the same result:

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

      

or simply:

arr[i] = i % 2;

      

+8


source


You can just do this :)



arr[i] = i%2;

      

+4


source


Because of problems with operator precedence, I believe that your code is processed as follows: (i % 2 == 0 ? arr[i] = 0 : arr[i]) = 1;

. Ternary operator creates rvalue

which in C cannot be assigned. You must change it toi % 2 == 0 ? (arr[i] = 0) : (arr[i] = 1);

In any case, this whole structure is superfluor, and it is better to replace it with something like arr[i] = i % 2;

+1


source


Why not:

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

      

0


source







All Articles