默认int类型:有符号还是无符号? [英] Default int type: Signed or Unsigned?

查看:3534
本文介绍了默认int类型:有符号还是无符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用类C语言编程时,应该将默认整数类型为int或uint / unsigned int?默认情况下,我的意思是当你不需要负数,但任何一个应该容易足够大的数据,你持有。我可以想到两个好的参数:



signed:在数学上更好的行为,如果你试图低于零在一些边界情况下,你没有' t想想,一般避免奇怪的角落情况更好。



unsigned:提供一个额外的保证,防止溢出,只是为了防止你对值的假设是错误的。

解决方案

Google C ++风格指南对无符号整数有一个有趣的意见: p>

(报价如下)



无符号整数 b

有些人(包括一些教科书作者)建议使用无符号类型来表示从不为负的数字。这是一种自我文档形式。然而,在C中,这样的文档的优点胜过它可以引入的真正的错误。考虑:

  for(unsigned int i = foo.Length() -  1; i> = 0; ... 

此代码永远不会终止!有时gcc会注意到这个bug并警告你,但通常不会。当比较有符号和无符号变量时,可能会出现同样糟糕的错误。基本上,C的类型提升方案会导致无符号类型的行为与预期不同。



因此,使用断言记录变量是非负数。不要使用未签名的类型。



(结束报价)


When programming in a C-like language should one's "default" integer type be int or uint/unsigned int? By default, I mean when you don't need negative numbers but either one should be easily big enough for the data you're holding. I can think of good arguments for both:

signed: Better-behaved mathematically, less possibility of weird behavior if you try to go below zero in some boundary case you didn't think of, generally avoids odd corner cases better.

unsigned: Provides a little extra assurance against overflow, just in case your assumptions about the values are wrong. Serves as documentation that the value represented by the variable should never be negative.

解决方案

The Google C++ Style Guide has an interesting opinion on unsigned integers:

(quote follows:)

On Unsigned Integers

Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider:

for (unsigned int i = foo.Length()-1; i >= 0; --i) ...

This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect.

So, document that a variable is non-negative using assertions. Don't use an unsigned type.

(end quote)

这篇关于默认int类型:有符号还是无符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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