Bartas Abaravičius Bartas Abaravičius - 22 days ago 10
C Question

If I pass an address of a variable do I have to do a return?

If I have a function that increments a global variable according to some rule and I pass a variable by reference, do I have to do a return or will the variable be updated anyway? Would this also work with a local variable? For example:

static uint8_t counter = 1;

void add(uint8_t *variable)
{
if (*variable == 5)
{
*variable = 7;

} else if (*variable == 20)
{
*variable = 1;
} else
{
*variable++;
}
}


And I call the 'add' function somewhere like:

void function(void)
{
... some code...
add(&counter);
... some code...
}

Answer

This code will work with any kind of variable whether it is global or local because the object is passed by reference.

However the better interface is when the function returns the pointer that it gets as the argument.

uint8_t * add(uint8_t *variable)
{
   if (*variable == 5)
   {
    *variable = 7;

   } else if (*variable == 20)
   {
    *variable = 1;
   } else
   {
    *variable++;
   }

  return variable;
}

In this case you can combine calls of the function or use it with other functions that await the same pointer. For example

add( add( &counter ) );

or

SomeOtherFunction( add( &counter ) );

A difference exists when the function is called in multi threaded environment and the global variable has no the storage class specifier _Thread_local.