0
void VoidRef (int &ref){
   ref++;
}

void VoidPtr (int *ptr){
  (*ptr)++;
}

int test= 5;

VoidRef(test);
cout << test;  // is 6

VoidPtr(&test);
cout << test;  // is 7 !

Why do both voids do the same thing? Which void needs more resources?

ollo
  • 24,797
  • 14
  • 106
  • 155
user1511417
  • 1,880
  • 3
  • 20
  • 41
  • 1
    Yes, they both do the same thing (though I'd go with the first one because it involves implementing a less intrusive syntax). – David G Apr 20 '13 at 22:15
  • A references is usually implemented as pointer under the hood so resource wise they should be the same. References in general should be preferred. – Shafik Yaghmour Apr 20 '13 at 22:15
  • The main advantage (IMO) of using a reference is it makes it impossible to accidentally pass a null or otherwise invalid pointer. – Jonathan Potter Apr 20 '13 at 22:17
  • possible duplicate of [What are the differences between pointer variable and reference variable in C++?](http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c) – David G Apr 20 '13 at 22:18
  • They're called "functions", not "voids". The "void" in the function declaration means the function doesn't return anything. And yes, pointers and references are quite similar. – Mike Seymour Apr 20 '13 at 23:04

1 Answers1

0
void VoidRef (int &ref){
              //^^pass by reference
   ref++;
}

void VoidPtr (int *ptr){
                //^^ptr stores address of test
  (*ptr)++;
}

Why do both voids do the same thing?

ref is a reference to test, i.e., an alias of test, so operation on ref is also operated on test.

ptr is a pointer that stores the memory address of test, so (*ptr)++ will increment the value that stored on the memory address by one. The reason that the first output is 6 and the second output is 7 since each call to those two functions increments the variable value by 1.

You can think of both VoidRef and VoidPtr operates on the address of the variable test, therefore, they have same effect.

taocp
  • 23,276
  • 10
  • 49
  • 62