使用-1作为无符号(为size_t)类型的标志值 [英] Using -1 as a flag value for unsigned (size_t) types

查看:136
本文介绍了使用-1作为无符号(为size_t)类型的标志值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是用-1作为它的返回类型是为size_t的函数的标志值(无符号型)。

我起初并不注意到它,特别是因为它并没有引起我的code的任何错误(0,我随x == -1,不是X&LT检查它)

有没有我不应该离开它,因为任何细微的原因是什么?当这可能会意外的行为?这是常用的?

ptrdiff_t的较少见,需要更长的时间打字,反正它,因为该函数返回一个索引到一个数组不是真正合适的类型。


解决方案

努力想办法,这可能出问题后,我意识到,有一种危险,即调用函数会返回值隐式转换为更大的类型(即unsigned int类型为unsigned long long)。然后检查是否该值== -1将是错误的。

较安全的选择是明确使用size_t.max作为标记值。我总是有符号和无符号类型之间的变化不舒服。有时候,我觉得比较合理的做法是只让一切符号(如Java一样)。

I was using -1 as a flag value for a function whose return type is size_t (an unsigned type).

I didn't notice it at first, particularly because it wasn't causing any errors in my code (I was checking it with x == -1, not x < 0).

Are there any subtle reasons I shouldn't leave it as is? When might this behave unexpectedly? Is this commonly used?

ptrdiff_t is less common, takes longer to type, and anyway it's not really the appropriate type since the function returns an index into an array.

解决方案

After trying to think of ways this might go wrong, I realized that there's a danger that the calling function might implicitly cast the return value to a larger type (ie unsigned int to unsigned long long). Then checking if that value == -1 will be false.

The safer option is to explicitly use size_t.max as the sentinel value. I'm always uncomfortable with changing between signed and unsigned types. Sometimes I think the more reasonable approach is to just make everything signed (like Java does).

这篇关于使用-1作为无符号(为size_t)类型的标志值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆