Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C functions overusing parameters?

Tags:

c

I have legacy C code base at work and I find a lot of function implementations in the style below.

char *DoStuff(char *inPtr, char *outPtr, char *error, long *amount)
{
    *error = 0;
    *amount = 0;

    // Read bytes from inPtr and decode them as a long storing in amount
    // before returning as a formatted string in outPtr.

    return (outPtr);
}

Using DoStuff:

myOutPtr = DoStuff(myInPtr, myOutPtr, myError, &myAmount);

I find that pretty obtuse and when I need to implement a similar function I end up doing:

long NewDoStuff(char *inPtr, char *error)
{
    long amount = 0;
    *error = 0;

    // Read bytes from inPtr and decode them as a long storing in amount.

    return amount;
}

Using NewDoStuff:

myAmount = NewDoStuff(myInPtr, myError);
myOutPtr += sprintf (myOutPtr, "%d", myAmount); 

I can't help but wondering if there is something I'm missing with the top example, is there a good reason to use that type of approach?

like image 207
sipsorcery Avatar asked Apr 07 '26 17:04

sipsorcery


1 Answers

One advantage is that if you have many, many calls to these functions in your code, it will quickly become tedious to have to repeat the sprintf calls over and over again.

Also, returning the out pointer makes it possible for you to do things like:

DoOtherStuff(DoStuff(myInPtr, myOutPtr, myError, &myAmount), &myOther);

With your new approach, the equivalent code is quite a lot more verbose:

myAmount = DoNewStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myAmount);
myOther  = DoOtherStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myOther);
like image 96
Eric Melski Avatar answered Apr 10 '26 11:04

Eric Melski