I'm confused why my compiler is throwing an error in the following condition:
void funcExample (void * p_Buf, uint16_t len)
{
uint16_t i;
for (i = 0; i < len; i++) {
otherFunc (((uint8_t *)p_Buf)++); //error = expression must be a modifiable lvalue
}
}
but if I cast prior to pass to otherFunc, it's fine because no problem incrementing a non-void pointer:
void funcExample (void * p_Buf, uint16_t len)
{
uint16_t i;
uint8_t * p_Buf_8bit;
p_Buf_8bit = (uint8_t *) p_Buf;
for (i = 0; i < len; i++) {
otherFunc (p_Buf_8bit++);
}
}
can't the void pointer be incremented once cast? am i missing something fundamental here?
Cast operators in c:
6.5.4. p5 Preceding an expression by a parenthesized type name converts the value of the expression to the named type. This construction is called a cast. 104) A cast that specifies no conversion has no effect on the type or value of an expression.
104) 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
But the unary operator ++
requires an lvalue as stated:
6.5.3.1. p1 The operand of the prefix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.
Therefore you can do:
p_Buf = ( uint8_t* )p_Buf + 1 ;
Where p_Buf
is lvalue and ( uint8_t* )p_Buf
is rvalue.
Let me just note that in your second example you don't cast( as you said ), but you declare a uint8_t pointer. Then when you use ++
on it you don't perform any casts( because it has the correct type ) and the operation is valid.
Incrementing a void
pointer in C
is bad idea. Most compilers don't even let it to be compiled. Use this instead:
p_Buf = (uint8_t*)p_Buf + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With