Like Tree1Likes
  • 1 Post By grumpy

Function as left hand operator error when returning pointer..

This is a discussion on Function as left hand operator error when returning pointer.. within the C++ Programming forums, part of the General Programming Boards category; Code: int * p=new int(); int* function () { *p=10; cout<<"old p :"<<*p<<endl; return p; } int main() { int ...

  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,203
    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).
    Sajas K K likes this.
    Right 98% of the time, and don't care about the other 3%.

  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,021
    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, 10: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, 04:50 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21