Difference between function arguments declared with & and * in C++

f2 is taking it’s arguments by reference, which is essentially an alias for the arguments you pass. The difference between pointer and reference is that a reference cannot be NULL. With the f you need to pass the address (using & operator) of the parameters you’re passing to the pointer, where when you pass by reference you just pass the parameters and the alias is created.

Passing by const reference (const double& ref) is preferred when you are not going to change the arguments inside the function, and when you are going to change them, use non-const reference.

Pointers are mostly used when you need to be able to pass NULL to your parameters, obviously you’d need to check then inside your function if the pointer was not NULL before using it.

Leave a Comment