【问题标题】:C - Returning negative value as unsigned sets errno?C - 返回负值作为无符号集 errno?
【发布时间】:2014-08-26 01:08:14
【问题描述】:

早安,

我正在阅读一些我被要求维护的旧代码,我看到了一些类似这样的函数:

uint32_t myFunc(int* pI);

在函数体内出现错误情况的情况下,函数通过返回一个负的errno值提前退出,即:return (-EINVAL);

这个值标准(即:C99、ANSI)、C 吗?我在 cmets 中读到显然这样做会将errno 设置为EINVAL,但我找不到任何文档来支持这一点。将函数声明为有符号整数(即:int32_t myFunc(int* pI))并将负值视为错误代码,而不是尝试以这种方式设置errno,不是更好吗?

【问题讨论】:

  • 我认为无论如何都不会返回任何错误...我认为您的负整数将被转换为无符号(负整数的相同二进制表示将用于您分配的无符号值)
  • 我想是的。使用正数这个地方很奇怪。至少它违反了 linux 约定。
  • 这是内核代码吗?
  • 对于这个 interesting 函数,当然 myFunc() 返回值 0 ... 0xFFFFFFFF-4096 是“正常”返回值,而 0xFFFFFFFF-4096+1 ... 0xFFFFFFFF 是"错误值。
  • @KeithThompson 不,这不是内核代码。

标签: c unsigned errno


【解决方案1】:

返回负值设置errno。这是您在上下文之外拾取的错误信息(或者更有可能是原作者拾取的):Linux 内核系统调用报告错误的机制正在返回范围内的负值-4095 到 -1,然后进行系统调用的用户空间代码(在大多数情况下)使用它来填充 errno 的值。但是,如果您想自己设置errno,只需为其赋值即可。

【讨论】:

    【解决方案2】:

    解决您的问题:这是价值标准(即:C99、ANSI)、C 吗?

    对于 C99

        "errno which expands to a modifiable lvalue that has type int, the
        value of which is set to a positive error number by several library
        functions." -- N1256 7.5p2
    

    对于 POSIX

        "The <errno.h> header shall define the following macros which shall
        expand to integer constant expressions with type int, distinct
        positive values" -- errno.h DSCRIPTION
    
        "Values for errno are now required to be distinct positive values
        rather than non-zero values. This change is for alignment with the
        ISO/IEC 9899:1999 standard." -- errno.h CHANGE HISTORY Issue 6 
    

    找到了一个很好的讨论(以及这些引用的来源)HERE(搜索“何时返回 EINVAL”)

    【讨论】:

      猜你喜欢
      • 2013-01-24
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 2010-12-23
      • 2023-03-25
      • 2013-03-27
      • 1970-01-01
      • 2014-07-15
      相关资源
      最近更新 更多