Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

zippyfly

macrumors regular
Original poster
Mar 22, 2008
141
0
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);
...
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.