0

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???

5
  • Doesn't compile in codepad (codepad.org/98m9rEjj). The problematic line indeed gives an error. What compiler did you use? Commented Apr 21, 2012 at 18:52
  • @ugoren remove two * from each sid eof the sentence, this is a formmating issue. Commented Apr 21, 2012 at 18:53
  • This code isn't legal C code. Lines 4 and 5 seem to have syntax errors. Commented Apr 21, 2012 at 18:53
  • 1
    @ssteinberg - line four is a valid function declaration, line 5 - see my previous comment. Commented Apr 21, 2012 at 18:57
  • this code is No problem. *(int pointer) = 5; //normal syntax Commented Apr 22, 2012 at 7:50

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

,@ugoren -how can *next() be an lvalue?? *next() is a function call which returns the address(a constant)..and how can a constant be an lvalue
*next() will not be an int. it will be an address pointing towards a integer value.
Not exactly, *next() is an int variable pointed by the return value of next.
2

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.