Vineeth bharadwaj
Vineeth bharadwaj

Reputation: 13

This statement gives an error saying "Expression must be a modifiable lvalue"

I have declared a two dimensional character array matrix[][].

char matrix[3][3] = {{' ', ' ', ' '},{' ', ' ', ' '},{' ', ' ', ' '}};

In a function vacantCenter(), I am trying to return 1, if matrix[1][1] stores a whitespace, else 0 if it doesn't.

int vacantCenter()
{
   int n;
   (matrix[1][1] == ' ')? n = 1: n = 0;
   return n;
}

A simple if case works fine. But the ternary operator shows an error saying "expression must be a modifiable lvalue". What's wrong in these lines? (I am using Visual Studio 2022; In a .c source file)

Upvotes: 0

Views: 110

Answers (2)

Fe2O3
Fe2O3

Reputation: 8344

Since it appears matrix is a global variable, you could just use something like:

#define VACANTCNTR (matrix[1][1] == ' ')

Then:

if( VACANTCNTR ) {
    ....
}

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

The precedence of the assigment operator = is lower than ther ternary operator ?:.

Therefore, your expression is interpreted as:

((matrix[1][1] == ' ')? n = 1: n) = 0;

Add parenthesis to make it work:

(matrix[1][1] == ' ')? n = 1: (n = 0);

Better thing is not to write such a tricky code. Your function vacantCenter can be written as:

int vacantCenter()
{
   return matrix[1][1] == ' ';
}

or (if you are not confident with how the == operator is evaluated):

int vacantCenter()
{
   return matrix[1][1] == ' ' ? 1 : 0;
}

Upvotes: 4

Related Questions