Difference in C++ and Obj-C handling of pass by reference?

Discussion in 'Mac Programming' started by zippyfly, Aug 25, 2009.

  1. zippyfly macrumors regular

    Joined:
    Mar 22, 2008
    #1
    Hi - I don't know C++ and am confused reading some C++ code (for learning):

    In the following code, the way the function takes the address of int a, and doubles it, seems weird; in C shouldn't we pass &a to the function and then dereference with *x *= 2 ??

    Or is that a typo in the C++ code I am reading?


    Code:
    void MyFunction (int &x)
    { x *= 2;
    }
    
    ...
    
    int main()
    {
    int a = 4;
    MyFunction (a);
    ...
    
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    Code:
    #include <iostream>
    void doubler(int &x);
    int main(int argc, char *argv[]) {
      int a = 4;
      std::cout << "Before call a: " << a << std::endl;
      std::cout << "Before call &a: " << &a << std::endl;
      doubler(a);
      std::cout << "after call a: " << a << std::endl;
      std::cout << "after call &a: " << &a << std::endl;
      return 0;
    }
    
    void doubler(int &x) {
      std::cout << "in call &x: " << &x << std::endl;
      x*=2;
    }
    
    Pass by reference in C++ is shorthand for passing a pointer. You just get the convenience of acting on the variable in the function as if it were local, and not having to dereference, etc. You still get the benefits of being able to modify the argument, and the pass via a pointer (which can save stack space, copy time, etc. with large objects or structures) without having to mess with * and & during the pass, in the destination, etc.

    I put the prints of the pointers in there to demonstrate that down in doubler you're dealing with the same bit of memory as in main.

    -Lee

    EDIT: You are right about the C syntax, it would look like:
    Code:
    #include <stdio.h>
    
    void doubler(int *x);
    
    int main(int argc, char *argv[]) {
      int a = 4;
      printf("In main at address %p a=%d\n",&a,a);
      doubler(&a);
      printf("In main after call, a=%d\n",a);
      return 0;
    }
    
    void doubler(int *x) {
      printf("In doubler, x is: %p\n",x);
      *x*=2;
    }
    
    I love C, but the C++ syntax for this is much nicer.
     
  3. zippyfly thread starter macrumors regular

    Joined:
    Mar 22, 2008

Share This Page