Let’s say you have a function that modifies a variable.
Should you write it like this: void myfunc(int *a) or like this void myfunc(int &a)?
The former forces you to call the function with myfunc(&b) so the caller is aware that b will be modified, but the latter is shorter and can be called simply with myfunc(b). So which is better to use? Is there something else I’m missing?
Pointers (ie. the ‘*’) should be used where the passing ‘NULL’ is meaningful. For example, you might use a NULL to represent that a particular object needs to be created, or that a particular action doesn’t need to be taken. Or if it ever needs to be called from non-C++ code. (eg. for use in shared libraries)
eg. The libc function
time_t time (time_t *result);If
resultis not NULL, the current time will be stored. But ifresultis NULL, then no action is taken.If the function that you’re writing doesn’t need to use NULL as a meaningful value then using references (ie. the ‘&’) will probably be less confusing – assuming that is the convention that your project uses.