Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - expression must be a modifiable lvalue

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?

like image 734
jaypee Avatar asked Oct 20 '14 16:10

jaypee


2 Answers

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.

like image 100
2501 Avatar answered Oct 06 '22 11:10

2501


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;
like image 32
Vladyslav Avatar answered Oct 06 '22 10:10

Vladyslav