Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the compiler generating an error "lvalue required"?

Tags:

c

pointers

lvalue

As per my understanding, in the line marked as 'line 2' of the below code, the expression (*ptr)++ should generate "lvalue required" error because *ptr evaluates to a constant value of i=1, which is not lvalue?

So why is the program working successfully? Or am I somewhere wrong in my concepts? If yes, please enlighten me on this.

int main(void)
{
    int i;
    int *ptr = (int *) malloc(5 * sizeof(int));

    for (i=0; i<5; i++)
        *(ptr + i) = i;

    printf("%d ", *ptr++);   //line 1
    printf("%d ", (*ptr)++); //line 2 
    printf("%d ", *ptr);     //line 3
    printf("%d ", *++ptr);   //line 4
    printf("%d ", ++*ptr);   //line 5
}
like image 538
codeluv Avatar asked Feb 09 '23 14:02

codeluv


1 Answers

You're having a misconception. result of (*ptr) is lvalue, upon which the post increment operator can be applied.

So, in your case,

 printf("%d ", (*ptr)++); //line 2

is fine.

To quote C11 standard, chapter §6.5.3.2, Address and indirection operators, (emphasis mine)

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.

FWIW, if *ptr would not be a lvalue, you would have got error for writing something like *ptr = 5 also, wouldn't it?

like image 91
Sourav Ghosh Avatar answered Mar 16 '23 10:03

Sourav Ghosh