gpt4 book ai didi

c++ - 解释为什么在 C++ 中应该首选 int 而不是 long/short?

转载 作者:太空狗 更新时间:2023-10-29 19:46:51 25 4
gpt4 key购买 nike

我在某处读到,无论操作系统如何,int 数据类型都能提供更好的性能(与 long 和 short 相比),因为它的大小会根据操作系统的字长进行修改。其中 long 和 short 分别占用 4 和 2 个字节,这可能与操作系统的字长匹配也可能不匹配。谁能对此给出一个很好的解释?

最佳答案

来自标准:
3.9.1,§2:

There are five signed integer types : "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment (44); the other signed integer types are provided to meet special needs.

所以你可以说 char <= short <= int <= long <= long long。
但是你不能说 short 是 2 个字节,而 long 是 4 个字节。

现在回答您的问题,大多数编译器将 int 与目标平台的寄存器大小对齐,这使得对齐更容易,并且在某些平台上的访问速度更快。但这并不意味着您应该更喜欢 int。
根据需要取数据类型。不要在没有性能度量的情况下进行优化。

关于c++ - 解释为什么在 C++ 中应该首选 int 而不是 long/short?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6491938/

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