Default value of errno variable [closed]

为君一笑 提交于 2019-12-07 16:47:34

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21025631/default-value-of-errno-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!