C functions using parameters?

I have a basic C code base at work, and I find many implementations of functions 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 this pretty dumb, 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 cannot help but wonder if there is something that I am missing in the above example, is there any good reason to use this approach?

+3
source share
5 answers

One of the advantages is that if you have many, many calls to these functions in your code, it will be very difficult for you to repeat the calls sprintfagain and again.

In addition, returning an out pointer allows you to do things like:

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

:

myAmount = DoNewStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myAmount);
myOther  = DoOtherStuff(myInPtr, myError);
myOutPtr += sprintf("%d", myOther);
+1

C. .

, DoStuff IMO. snprintf. . NewDoStuff.

+1

(, myOutPtr sprintf.

, , , , , , , , , , - ().

- . , , .

, , , . , , ( C) -, DoStuff.

, . , OOP, , ( ). , .

0

sprintf NewDoStuff, (, , DRY). , -, , .

0

, 110 , ( ). , (-) , , 5 5 , , .

, C.

0

Source: https://habr.com/ru/post/1705618/


All Articles