0

So I've started learning about pointers in C++. On the topic of passing pointers to functions, I've seen two different possible implementations:

1.

#include <stdio.h>

void multiplyBy2(int *num);

int main(int argc, char *argv[]) {
    int six = 6;
    printf("%d\n", six);
    multiplyBy2(&six);
    printf("%d\n", six);
}

void multiplyBy2(int *num) {
    *num *= 2;
}

2.

#include <stdio.h>

void multiplyBy2(int &num);

int main(int argc, char *argv[]) {
    int six = 6;
    printf("%d\n", six);
    multiplyBy2(six);
    printf("%d\n", six);
}

void multiplyBy2(int &num) {
    num *= 2;
}

Both of these, when compiled and run, have the exact same output:

6
12

My question is, is there any difference between these to implementations, and is one better than the other?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
tarunbod
  • 67
  • 1
  • 2
  • 9
  • 4
    The second is not legal in C. – EOF Aug 18 '16 at 22:06
  • 1
    One of them is C (`*`) and the other is not (`&`). One of them is called a pointer (`*`), and the other is not (`&`) – Antti Haapala -- Слава Україні Aug 18 '16 at 22:06
  • 2
    Only in the first case are you passing a pointer. In the second case, you are passing the argument by reference, which is permitted only in C++, not C. They have slightly different semantics. – John Bollinger Aug 18 '16 at 22:06
  • Using pointers is less safe. – πάντα ῥεῖ Aug 18 '16 at 22:08
  • @πάνταῥεῖ that generalization can get you in trouble. http://stackoverflow.com/a/57656/5987 – Mark Ransom Aug 18 '16 at 22:32
  • The implementation that takes a pointer as a parameter must check for NULL before using the pointer, or your program will crash when NULL is passed in. The implementation that takes a reference does not need to check the reference, the caller will always have to pass something in. However, both implementations may get uninitialized values passed in. – regmagik Aug 18 '16 at 22:37
  • @MarkRansom I didn't say it's invalid. For the given context of passing parameters, (`const`) references should be preferred whenever possible. Nice example of undefined behavior BTW. – πάντα ῥεῖ Aug 18 '16 at 22:41
  • Once you learn pros and cons of pointers and references, consider designing your program with side-effect-free functions:int multiplyBy2(int num) { return num * 2; } and then use it like this int six = 6; six = multiplyBy2(six); – regmagik Aug 18 '16 at 22:42

0 Answers0