Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of errno variable [closed]

Tags:

c

errno

I want to use the errno library in order to define the return of a project (c language) functions. And I'm wondering about something...

I will do something like this :

#include <errno.h>

int myfunction (void)
{
  int res;

  /*Some actions....*/

  if(success)
    res = 0;
  else if (fail)
    res = -EIO;

  return res;
 }

I like to always initialize my local variable and I am wondering what should be the default value of a variable using the errno value (probably 0) ? But I don't really like to set by default : "SUCCESS" I prefer a "Failure" value. What is your point of view (or rule) about it ?

Thanks by advance.

like image 934
Joze Avatar asked Feb 15 '23 04:02

Joze


2 Answers

If your question is what the default, no error, value is for errno and all the functions that return error status in errno, that value is 0 as you expect.

But the error code is usually not returned as a negative value to the caller as you have it in your snippet.

like image 98
Jens Gustedt Avatar answered Feb 24 '23 10:02

Jens Gustedt


There is no EGENERIC/EUNKNOWN value defined as some general error indicator.

You have the following options:

  • Be optimistic and set the default result to 0 indicating success.
  • Use a function specific default out of the set of values defined for errno.
  • If returning negative values for errno use 1 as generic error value.
  • Use positive errno value and use -1 as generic error indicator.

For the last options also set errno inside your function.


Update on POSIX systems

If going to use the value defined for errno there is no portable way to use any other value but 0, as POSIX explicitly states:

Only the macro names *1 should be used in programs, since the actual value of the error number is unspecified.

*1 This referrs to the Exyz macros, as listed here.

like image 32
alk Avatar answered Feb 24 '23 09:02

alk