Topic : Post increment operator

Forum : ST7/STM8

Original Post
Post Information Post
November 4, 2010 - 8:28pm
Guest

The compiler does not correctly apply post increment operator on these instructions:

 int i = 0;
 long l = 0x0102;
 void *addri = (void*)&i;
  
  *((int*)addri++) = l;
  printf ("%s works\r\n",  (&i + 1 == addri) ? "" : "not");

This code compiles but it behaves wrongly because the post increment adds just 1 to addri because the compiler doesn't know the actual size of addri. It shouldn't compile rather than produce a wrong result.

When you try to cast the addri pointer to the correct size it doesn't compile:

 int i = 0;
 long l = 0x0102;
 void *addri = (void*)&i;
  
  *(((int*)addri)++) = l;
  printf ("%s works\r\n",  (&i + 1 == addri) ? "" : "not");

It says the "operand is an lvalue". Other compiler works and produce the correct result.
To overcome this error you must copy back and forth addri to another typed pointer!

Regards.

Replies
Post Information Post
+1
0
-1
November 8, 2010 - 11:29am
Raisonance Support Team

Hi,

The ANSI/ISO C Standard mandates that "A cast does not yield an lvalue. Thus, a cast to a qualified type has the same effect as a cast to the unqualified version of the type."

In other words, you cannot cast the left-side of an assignment or of a address-of operator. As the postincrement operator "++" is an affectation operator, the conversion is not allowed.

So our compiler is perfectly right and MUST reject your "*((int*)addri++) = l;" statement.

The best workaround is to use the proper pointer type instead of "void *". Alternatively, you can assign a "char *" pointer to your pointer's value and manipulate it freely.

Regards,

+1
0
-1
November 8, 2010 - 12:40pm
Guest

Bruno,
ok, if the compiler is strictly ANSI compliant you're right. But the rejected statement is

*(((int*)addri)++) = l;

not this:

*((int*)addri++) = l;

Regards.

+1
0
-1
November 8, 2010 - 3:53pm
Raisonance Support Team

Right, the problem comes from the postincrement operator (++), which requires its operand being an lvalue.

Regards,