为什么喜欢在C ++中签名未签名? [英] Why prefer signed over unsigned in C++?

查看:190
本文介绍了为什么喜欢在C ++中签名未签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更好地了解为什么选择 int 无符号



就我个人而言,除非有合理的理由,否则我从来不喜欢签名值。例如数组中的项目的计数,字符串的长度或存储器块的大小等,所以经常这些东西不可能是否定的。这样的值没有可能的意义。



我问这个问题,因为Bjarne Stroustrup和Chandler Carruth都是这样的人,所以为什么选择 int 给予建议优先 int over unsigned 这里(约12:30)



我可以看到使用 int - int 是目标机架构的最自然的数据宽度。



但是签名的unsigned总是恼火的。在典型的现代CPU架构上,签名值真的更快吗?

解决方案

让我来解释视频,正如专家们所说的那样。


Andrei Alexandrescu




  • 没有简单的指南

  • 在系统编程中,我们需要不同大小和签名的整数。

  • 许多转换和奥术规则管理算术
    <$> >:




    • 以下是一些简单的指南:


      1. 使用有符号整数,除非你需要两个

      2. 否则,使用 int

      3. 如果您认为可以对项目进行计数,请输入64位整数,


    Bjarne Stroustrup 不要担心并使用工具来告诉您何时需要不同的类型或大小。 >:




    • 使用 int ,直到您有原因为止。



    >

    对于签名规则的保守性,我的一句话从专家身上删除:


    使用适当的类型,当您不知道时,使用 int ,直到您知道。



    I'd like to understand better why choose int over unsigned?

    Personally, I've never liked signed values unless there is a valid reason for them. e.g. count of items in an array, or length of a string, or size of memory block, etc., so often these things cannot possibly be negative. Such a value has no possible meaning. Why prefer int when it is misleading in all such cases?

    I ask this because both Bjarne Stroustrup and Chandler Carruth gave the advice to prefer int over unsigned here (approx 12:30').

    I can see the argument for using int over short or long - int is the "most natural" data width for the target machine architecture.

    But signed over unsigned has always annoyed me. Are signed values genuinely faster on typical modern CPU architectures? What makes them better?

    解决方案

    Let me paraphrase the video, as the experts said it succinctly.

    Andrei Alexandrescu:

    • No simple guideline.
    • In systems programming, we need integers of different sizes and signedness.
    • Many conversions and arcane rules govern arithmetic (like for auto), so we need to be careful.

    Chandler Carruth:

    • Here's some simple guidelines:

      1. Use signed integers unless you need two's complement arithmetic or a bit pattern
      2. Use the smallest integer that will suffice.
      3. Otherwise, use int if you think you could count the items, and a 64-bit integer if it's even more than you would want to count.

    • Stop worrying and use tools to tell you when you need a different type or size.

    Bjarne Stroustrup:

    • Use int until you have a reason not to.
    • Use unsigned only for bit patterns.
    • Never mix signed and unsigned

    Wariness about signedness rules aside, my one-sentence take away from the experts:

    Use the appropriate type, and when you don't know, use an int until you do know.

    这篇关于为什么喜欢在C ++中签名未签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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