【发布时间】:2017-04-11 04:19:07
【问题描述】:
让我对常规 c 整数声明感到困扰的一件事是它们的名称很奇怪,“long long”是最糟糕的。我只为 32 位和 64 位机器构建,所以我不一定需要该库提供的可移植性,但是我喜欢每种类型的名称都是长度相似的单个单词,大小没有歧义。
// multiple word types are hard to read
// long integers can be 32 or 64 bits depending on the machine
unsigned long int foo = 64;
long int bar = -64;
// easy to read
// no ambiguity
uint64_t foo = 64;
int64_t bar = -64;
在 32 位和 64 位机器上:
1) 使用较小的整数(例如 int16_t)会比使用较大的整数(例如 int32_t)慢吗?
2) 如果我需要一个 for 循环来运行 10 次,是否可以使用可以处理它的最小整数而不是典型的 32 位整数?
for (int8_t i = 0; i < 10; i++) {
}
3) 每当我使用我知道永远不会为负的整数时,即使我不需要提供的额外范围,是否可以更喜欢使用无符号版本?
// instead of the one above
for (uint8_t i = 0; i < 10; i++) {
}
4) 对 stdint.h 中包含的类型使用 typedef 是否安全
typedef int32_t signed_32_int;
typedef uint32_t unsigned_32_int;
编辑:两个答案都一样好,我不能真正倾向于一个,所以我只选择了代表较低的回答者
【问题讨论】:
-
它们很相似,但是我有一些关于如何实现它们的具体问题,但在那篇文章中没有明确回答。此外,该帖子的最佳答案听起来像是固定类型不会出错,但根据下面的两个答案,这不一定是正确的。