Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading