Pass variable by reference or value
In a recent project with an ATtiny3217 I faced some very strange behaviours, where values passed to functions didn't stay the same. What looked first as a Heisenbug, revealed to be a bad coding pattern.
It raised the question if I should pass variables by reference or value?
The answer is pretty simple for such small MCU's. Anything above simple uint8_t or uint16_t should be passed by reference, as also pointed in stackoverflow.
There's basically 2 ways to pass a variable by its reference. Let's have the following example:
uint8_t variable = 12;
typedef struct {
uint8_t x;
uint8_t y;
} SOMESTRUCT;
SOMESTRUCT obj = { .x=1, .y=2 };
Pass by pointer
function do_something(uint8_t *argument, SOMESTRUCT *object) {
*argument = 10;
object->x = 2;
}
do_something(&variable, &some_struct);
Pass by reference
function do_something(uint8_t& argument, SOMESTRUCT &object) {
argument = 10;
object.x = 2;
}
do_something(variable, obj);
You can find some more details at eg geeksforgeeks.