Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why foo((&i)++) gives Lvalue required error. There is no array associated

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)++); ^

like image 631
likeicare Avatar asked Nov 11 '17 02:11

likeicare


People also ask

Why do programers use foo?

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.

Why are functions named foo?

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).


2 Answers

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.

like image 106
kadina Avatar answered Oct 06 '22 00:10

kadina


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.

like image 23
msc Avatar answered Oct 06 '22 00:10

msc