Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to return value from function, and when to use out parameter? [closed]

Tags:

c

I'm learning C and programming in general, and I don't know when to return a value and when to use void.

Is there any rule to apply when to use one over the another ?

Is there any difference between this two cases? I know that first case is working with a local copy of int (n) , and second with original value.

#include <stdio.h>

int case_one(int n)
{
    return n + 2;
}

void case_two(int *n)
{
    *n = *n + 2;
}

int main(int argc, char *argv[])
{
    int n = 5;
    n = case_one(n);
    printf("%i\n", n);

    n = 5;
    case_two(&n);
    printf("%i\n", n);

    return 0;
}
like image 947
HelloWorld Avatar asked Sep 14 '26 23:09

HelloWorld


1 Answers

There is one more reason to use out param instead of return value - error handling. Usually return value (int) of the function call in C represents success of the operation. Error represented by not 0 value. Example:

#include <stdio.h>

int extract_ip(const char *str, int out[4]) {
    return -1;
}

int main() {
    int out[4];
    int rv = extract_ip("test", out);

    if (rv != 0) {
       printf("Error :%d", rv);
    };
}

This approach used in POSIX socket API for example.

like image 111
j2ko Avatar answered Sep 17 '26 11:09

j2ko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!