Arduino Pointers or References?

Is there a preference among us when “passing” a variable to a function in the firmware to use a Pointer or a Reference?

It seems like a controversial topic when I look on the interwebs. I realize they are different and each have their valid uses. But in the case of calling a function is there any optimization benefit of one over the other?

I am less likely to make a coding error when using references in this instance, but I see that a lot of pointers were used in the kinematics code.

I don’t have strong feelings about this. I think that the current system comes mostly from different people having different opinions.

Maybe we should pick a style guide to follow? (Although style guides rarely go into this level of detail)

1 Like

KrKeegan,
My only comment would be to do with persistence of the change. If you pass by reference the change is visible outside the local scope of the function where as passing a variable the change only has local scope and is not persistent outside the function call.

Is this what you were asking?

Stuart

Sorry I misread. Both pointers and references were mentioned. Both will be persistent outside local scope.

Sorry Stuart

Ugh, my brain hurts trying to keep these concepts sorted.

I did discover an instance in which pointers are very helpful. In places were you would have the same data stored in ram twice. It is a bit nuanced, but for classes, we have class variables that store values present in our system settings store.

For example, the axis class has variables for Kp and which are also in the settings store. The axis code can’t reference the system settings store directly because each axis has different settings and different names (it actually could using some really messy and ugly logic statements).

However, this is the right use of a pointer. The class variable is now just a pointer to the system settings store. I shaved off 18 bytes already, but I suspect I can get another 70 bytes or so, which is good, because my settings storage implementation is eating up about 128 bytes of ram.

3 Likes