Thread: pass by referrence

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    1

    Red face pass by referrence

    below is a code in c

    void afunction(int *x)
    {
    x=new int;
    *x=12;
    }
    int main()
    {
    int v=10;
    afunction(&v);
    cout<<v;
    }
    i thinkthe answer should be 12,but according to an answer given by one expert is 10.please explain.

  2. #2
    Registered User pinko_liberal's Avatar
    Join Date
    Oct 2001
    Posts
    284
    This is not a code in C.
    Last edited by pinko_liberal; 02-24-2003 at 04:10 PM.
    The one who says it cannot be done should never interrupt the one who is doing it.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You are on the wrong board. This is C++ code.

    The correct answer is 10.
    Code:
    void afunction(int *x)
    {
    x=new int; // new is a C++ keyword
    *x=12; //x is now a new integer, not the first
    }
    This new variable is gone at the end of this function call. You are not updating the initial pointer, you are allocating a new one, which the original variable does not point to. (For one, because it is not a pointer, but an actual int.)

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    Registered User geqo's Avatar
    Join Date
    Jan 2003
    Posts
    2
    no, that wasn't c code.
    also, nothing will happen when you try to assign a new address to the address of a variable. it'd be almost like doing:
    Code:
    void fisk(int kalas) { kalas = 5; }
    
    int main() { fisk(7); }
    and hoping that something extra-ordinary would occur.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Speed test result
    By audinue in forum C Programming
    Replies: 4
    Last Post: 07-07-2008, 05:18 AM
  2. Replies: 3
    Last Post: 11-22-2007, 12:58 AM
  3. pass by referrence
    By Unregstered in forum C++ Programming
    Replies: 3
    Last Post: 02-16-2003, 07:41 PM
  4. pass be reference versus pass by value
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 08-01-2002, 01:03 PM
  5. Replies: 3
    Last Post: 04-02-2002, 01:39 PM