Thread: Function as left hand operator error when returning pointer..

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    13

    Question Function as left hand operator error when returning pointer..

    Code:
    int * p=new int();
    int* function ()
    {
        *p=10;
        cout<<"old p :"<<*p<<endl;
        return p;
    }
    int main()
    {
        int c=25;
        function()=&c;
        cout<<*p<<endl;
    }
    Gives an error saying function on lefthand side.

    Code:
    int * p=new int();
    int& function ()
    {
        *p=10;
        cout<<"old p :"<<*p<<endl;
        return *p;
    }
    int main()
    {
        int c=25;
        function()=c;
        cout<<*p<<endl;
    }
    Works fine.

    Why does the second one works fine but not the first one?
    The code that i wrote may not make any sense.. Sorry.. I just wanted to know why the first one won't compile..

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    If a function returns a value rather than a non-const reference, that return value is an rvalue. An rvalue cannot be on the left hand side of an assignment.

    A pointer is not a reference - like an int, it is something with a type and a value (which happens to be the address of something else or NULL, if properly initialised).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    13
    Thanks.. And Sorry.. For asking such a stupid question.. What i wanted in my project was to change the address pointed to by the pointer.. I could have just returned a reference to the pointer, like int*& function().. Thanks again..

  4. #4
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Yeah you could.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 11-27-2012, 11:54 AM
  2. Replies: 24
    Last Post: 04-19-2012, 04:51 AM
  3. warning: left-hand operand of comma has no effect
    By musicalhamster in forum C++ Programming
    Replies: 7
    Last Post: 07-22-2008, 04:43 AM
  4. function returning pointer
    By blue_gene in forum C Programming
    Replies: 7
    Last Post: 04-19-2004, 02:35 PM
  5. left hand opperand??
    By Megatron in forum C++ Programming
    Replies: 8
    Last Post: 03-27-2002, 05:50 PM

Tags for this Thread