Raj
Raj

Reputation: 51

functions returning pointers

I came across a program in c:

int bags[5]={20,5,20,3,20};
int main()
{
    int pos=5,*next();
    *next()=pos;   //problem with this line(should give error :lvalue required)
    printf("%d %d %d",pos,*next(),bags[0]);
    return 0; 
}
int *next()
{
    int i;
    for(i=0;i<5;i++)
        if(bags[i]==20)
            return (bags+i); 
    printf("error");
    exit(0);
}

the output to the program is 5 20 5 though i expected it to be lvalue required. can anyone tell the reason???

Upvotes: 0

Views: 171

Answers (3)

bames53
bames53

Reputation: 88155

The result of the dereference operator * is an lvalue.

"The unary * operator denotes indirection. [...] if it points to an object, the result is an lvalue designating the object." C99 6.5.3.2/4

Upvotes: 0

ugoren
ugoren

Reputation: 16441

next() is not an lvalue, because function return values are not.
*next() is an lvalue, because its a value contained at some known memory address. Whether this address was obtained as a function's return value or otherwise (e.g. it was stored in a variable), doesn't matter.

Upvotes: 2

MByD
MByD

Reputation: 137272

While next() is not lvalue, *next() is, this is an int, addressed by the return value if *next()(which is an int in thebags` array).

In other words, while you can't assign to the return value of a function, you can assign to the value which is addressed by the return value.

Upvotes: 2

Related Questions