For simple cases such as a function which simply returns an int, first style is much clearer and straightforward.
The second style is preferred in certain cases, for example, if you want to get multiple values returned from the function. As per the C standard a function can return only one value, therefore to get a second value back, you can pass a pointer to the function, which the function can update. Following is a hypothetical example to illustrate this:
char *getline(FILE *f, int *size);
Consider a function getline
which returns a string representing a line from the file, and since it is reading a line, you must want to know the length of the line as well, and to get that, you pass a pointer to an int to the function, which it will update after reading the line. This is good from performance point of view as well, because the function getline
, in this case is doing the hardwork of scanning the characters from the file, so it might as well give us back the size of the line. Otherwise, after getting the string back, you would have to call strlen()
yourself, which would repeat the same task. This small trick can help save many CPU instructions in performance critical code.