Ignore output parameters in C

Viewed 87

I have a function which returns some value and some parameters:

uint8 myFunction(uint8* param1);

uint8 myFunction(uint8* param1)
{
    *param1 = 3;

    return 1;
}

Later in my code I would like to use the function once with returning a value like:

uint8 a;
uint8 b;

a = myFunction(b);

...
...

and once with just ignoring the parameter, like:

a = myFunction(void);

How to do this in C?

1 Answers

I'd recommend adding a NULL check before dereferencing param1 - that would be wise anyway. Then you can just pass NULL where you want to ignore it.

uint8 myFunction(uint8* param1)
{
    if (param1 != NULL)
    {
        *param1 = 3;
    }

    return 1;
}

calling code can then just pass NULL:

a = myFunction(NULL);

Of course, it would be good to clearly document this behavior.

Related