簡體   English   中英

C-以無符號形式返回負值會導致errno嗎?

[英]C - Returning negative value as unsigned sets errno?

美好的一天,

我正在閱讀一些要求維護的舊代碼,並且看到許多類似的功能:

uint32_t myFunc(int* pI);

如果函數體內出現錯誤情況,則函數會通過返回負errno值而提前退出,即: return (-EINVAL);

這個值是標准值(例如:C99,ANSI),C嗎? 我已經讀過評論,顯然這樣做可以將errnoEINVAL ,但是我找不到任何文檔來支持此操作。 僅將函數聲明為帶符號的int(即: int32_t myFunc(int* pI) )並將負值視為錯誤代碼,而不是嘗試以此方式設置errno ,會更好嗎?

返回負值不會設置errno 這是您錯誤地(或更可能是原始作者所錯誤地)獲取的錯誤信息: Linux內核系統調用報告錯誤的機制返回的負值在-4095到-1之間,然后,進行系統調用的用戶空間代碼將使用(在大多數情況下)填充errno的值。 但是,如果要自己設置errno ,則只需為其分配一個值。

解決您的問題: 此值是否為標准值(即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 

這里找到了很好的討論(以及這些引文的出處)(搜索“何時返回EINVAL”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM