Expression must be a modifiable lvalue

Technical Note 82120

Arkitekturer:

All

Komponent:

compiler

Uppdaterad:

2015-11-06 10:03

Introduction

You may encounter the following message if you move code to another version of the IAR C/C++ Compiler:

Error[Pe137]: expression must be a modifiable lvalue

This message occurs because a cast does not produce an lvalue (that is, a 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.

All product names are trademarks or registered trademarks of their respective owners.

Det här innehållet finns tyvärr inte på svenska.

Vår webbplats finns främst på vårt koncernspråk engelska, förutom det innehåll för investerare som vi är lagstadgade att kommunicera på svenska. Vi rekommenderar att du besöker vår globala webbplats på engelska för att få en bättre upplevelse.

Vi stöder inte längre Internet Explorer. För att få bästa möjliga upplevelse av iar.com rekommenderar vi att du uppgraderar till en modern webbläsare som Chrome eller Edge.