Functions returning Error codes or actual info

Vasile R. Montan vrm at cathedral.cerc.wvu.wvnet.edu
Tue Sep 11 00:11:18 AEST 1990


   I am making a set of functions which return different types of
values: strings, integers, doubles, etc.  For example:
          char *get_string();
However, I would also like the function to return an error code if the
function fails.  I cannot just return a NULL pointer because I want
the function to be the same as all of the other get_xxx's. I have seen
this done several different ways in C and am wondering if there is an
accepted "proper" way of doing it.

Most often in C, I see the error code being returned so it can be used
inside a control statement.  This forces the actual information to be
returned in an "out" mode parameter:

CASE 1:	if (error_code = get_string(parm, &info)) {...}

I have also seen functions which set a global variable to indicate
that an error has occurred:

CASE 2:	info = get_string(parm);
	if (error_code) {...}

I have not seen these used often, but they are also valid options:

CASE 3:	info = get_string (parm, &error_code);
	if (error_code) {...}

CASE 4:	get_string (parm, &info, &error_code);
	if (error_code) {...}

   BTW, I have some other functions which do not return any
information, so they always return an error code.  Does this mean I
should use CASE 1 just to keep them consistent?

   So, which do you feel is the best way to implement these functions?
This has probably been discussed here before, but I missed it.  If it
has and someone has saved the discussion, I would like to see it.  If
it has not, I would like to hear everyone's opinion.  I will summarize
any responses I receive.

-- Vasile



More information about the Comp.lang.c mailing list