简体   繁体   中英

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)

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

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

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

Then:

if( VACANTCNTR ) {
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM