I understand a few things about Lvalue but I don't understand how the below code gives an error:
#include<stdio.h>
void foo(int *);
int main()
{
int i=10;
foo((&i)++);
}
void foo(int *p)
{
printf("%d",*p);
}
6:13: error: lvalue required as increment operand foo((&i)++); ^
Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program.
This probably comes from the FUBAR acronym, which stands for F***ed Up Beyond All Repair , and quickly got adapted into programming as foobar , and then foo , bar (and baz as an addition).
x++ results following steps.
1) read the value of x in to register.
2) increment the value of x
3) write the incremented value back to x (which means you are changing the value of x by '1')
But what you are trying to do is (&i)++ which means the following.
1) read address of i into register
2) increment the address by 1
3) write the incremented value in to address again? How you can change the address?
If you want to send the integer which is stored in next address to foo(), you need to increment as below.
int *p = &i + 1;
foo(p);
But that may result in undefined behavior because you know only address of i where i value is stored. Once you increment the address, you will get next address and it may contain some junk value.
There is an attempt to apply the unary operator &
to a temporary object that is evaluated as the expression (&i)++
. You may not apply the operator to a temporary object.
C Standard (6.5.3.2 Address and indirection operators):
1 The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.
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