gpt4 book ai didi

将未知类型与负值进行比较

转载 作者:行者123 更新时间:2023-12-04 02:46:29 24 4
gpt4 key购买 nike

我有一个变量 id,其类型可能因平台而异。在几个地方,现有代码(我无法更改)将 id 设置为“负”值,例如

id = -ETIMEDOUT;

在某些平台上,id 可能被签名;在其他人身上,它可能没有签名。我想测试一下 id 是否设置为 -ETIMEDOUT。当 id 未签名时,下面的天真尝试巧妙地失败了:

if(id == -ETIMEDOUT)

我该如何简洁地测试这种情况?

最佳答案

@jlahd 发布了一个很好的答案。不过,我想提供一个替代方案。

if (id == (typeof(id)) -ETIMEDOUT)

我认为这会做类似的事情,但它有一个问题。它不在 C 标准中,而是 GCC 扩展。

您可以阅读更多相关信息 here

逐字引用@rici 的评论:

Since you probably know some typedef which works as the type of id, you can presumably do this without typeof, although that is cleaner. However, it should be

(typeof(id))(-ETIMEDOUT) 

(the parentheses around -ETIMEDOUT are just cosmetic but the unary minus is required.) Alternatively, the following should be pretty well foolproof:

if (-id == ETIMEDOUT)

since if id is signed, that obviously works; if id is unsigned, then unary minus has well-defined behaviour.

关于将未知类型与负值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18729632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com