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

Time:07-17

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)

CodePudding user response:

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;
}
  • Related