Technical Note 82120

Expression must be a modifiable lvalue error

EW targets: All
EW component: C/C++ compiler
Keywords: ANSI C standard, C code, C compiler, Error ###, lvalue
Last update: August 1, 2003
Problem

You may encounter the following error message if you move code to a more recent IAR C compiler:

Error[Pe137]: expression must be a modifiable lvalue

This error message occurs because a cast does not produce an lvalue (value that can be used on the left side of an assignment).

Also note that a casted expression that is used with the * operator does produce an lvalue, which is why the following is OK:

void f (void * ptr)
{
  *(long *)ptr = 0x11223344L;
}
How to get rid of the error message

There are a couple of ways to rework the code to avoid this error message.

The best way is probably to rework the types so that the cast do not appear in the first place, if possible.

An alternative is to use a temporary variable of the desired type.

The following example fails:

void f (void *ptr)
{
  ((short *)ptr)++; // error
}

You can rewrite it to:

void f (void *ptr)
{
  short *temp = ptr;
  temp++;
  ptr = temp;
}
Technical details

The reason why it does not work is that a cast does not produce an lvalue (ISO/ANSI 9899-1990 6.3.4 and Annex B which describes the syntax of C).

From ISO/ANSI 9899-1990 6.3.4, cast operators, footnote 44: "A cast does not yield an lvalue. [...]".

An extract from Annex B follows below:

unary-expression:
  postfix-expression
  ++ unary-expression
  -- unary-expression
  unary-operator cast-expression
  sizeof unary-expression
  sizeof ( type-name )

unary-operator: one of
  & * + - ~ !

cast-expression:
  unary-expression
  ( type-name ) cast-expression

conditional-expression:
  logical-OR-expression
  logical-OR-expression ? expression : conditional-expression

assignment-expression:
  conditional-expression
  unary-expression assignment-operator assignment-exression

assignment-operator: one of 
  = *= /= %= += -= <<= >>= &= ^= |=

The assignment requires a unary-expression on the left side. A cast-expression is not part of a unary-expression. As mentioned above, you can use a unary-operator before the cast-expression to get a unary-expression, such as '*'.

Many compilers permit cast expressions on the left side of an assignment, including several produced by IAR Systems. We have since then switched to another C parser that is more restrictive on this, and besides, it is not proper ISO/ANSI C code.