I was given some code in which some of the parameters are pointers, and then the pointers are dereferenced to provide values. I was concerned that the pointer dereferencing would cost cycles, but after looking at a previous StackOverflow article: How expensive is it to dereference a pointer?, perhaps it doesn't matter.
Here are some examples:
bool MyFunc1(int * val1, int * val2)
{
*val1 = 5;
*val2 = 10;
return true;
}
bool MyFunc2(int &val1, int &val2)
{
val1 = 5;
val2 = 10;
return true;
}
I personally prefer the pass-by-reference as a matter of style, but is one version better (in terms of process cycles) than another?
I read about * referencing operator and & dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to.
Passing by pointer Vs Passing by Reference in C++ Only difference is that References are used to refer an existing variable in another name whereas pointers are used to store address of variable. It is safe to use reference because it cannot be NULL.
Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
As opposed to referencing a data value, a function pointer points to executable code within memory. Dereferencing the function pointer yields the referenced function, which can be invoked and passed arguments just as in a normal function call.
My rule of thumb is to pass by pointer if the parameter can be NULL, ie optional in the cases above, and reference if the parameter should never be NULL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With