Thread: Return values and pointers

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    2

    Return values and pointers

    I am curious on how the return values work.

    I know the basics.

    Code:
    int x;
    
    int getMyInt() {
    return x;
    }
    
    void test() {
    modify(getMyInt());
    }
    
    void modify(int y) {
    y = 3;
    }
    Can someone explain how the data flow works here?

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    'modify' has no effect on the variable passed into it because you are passing by value.
    To see why y is just a copy of the parameter, consider that it is perfectly okay to do:
    Code:
    modify(42);
    This clearly does not make 42 equal to 3.

    What you want is to pass by reference.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to use return values
    By Furious5k in forum C++ Programming
    Replies: 3
    Last Post: 02-05-2009, 09:07 PM
  2. Replies: 4
    Last Post: 03-11-2005, 05:45 PM
  3. return values
    By C++Child in forum C++ Programming
    Replies: 5
    Last Post: 07-21-2004, 06:16 PM
  4. Return values
    By Juganoo in forum C Programming
    Replies: 2
    Last Post: 01-03-2003, 09:28 PM
  5. Return Values ( C )
    By Inept Pig in forum C Programming
    Replies: 2
    Last Post: 04-16-2002, 10:02 AM