c - Why isn't the compiler generating an error "lvalue required"? -
as per understanding, in line marked 'line 2' of below code, expression (*ptr)++
should generate "lvalue required" error because *ptr
evaluates constant value of i=1
, not lvalue?
so why program working successfully? or somewhere wrong in concepts? if yes, please enlighten me on this.
int main(void) { int i; int *ptr = (int *) malloc(5 * sizeof(int)); (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 }
you're having misconception. result of (*ptr)
is lvalue, upon post increment operator can applied.
so, in case,
printf("%d ", (*ptr)++); //line 2
is fine.
to quote c11
standard, chapter §6.5.3.2, address , indirection operators, (emphasis mine)
the unary
*
operator denotes indirection. if operand points function, result function designator; if points object, result lvalue designating object.
fwiw, if *ptr
not lvalue, have got error writing *ptr = 5
also, wouldn't it?
Comments
Post a Comment