C中数组索引的正确类型是什么? [英] What is the correct type for array indexes in C?

查看:284
本文介绍了C中数组索引的正确类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该使用C99中的数组索引的类型?它必须适用于LP32,ILP32,ILP64,LP64,LLP64等。它不一定是C89类型。

What type for array index in C99 should be used? It have to work on LP32, ILP32, ILP64, LP64, LLP64 and more. It doesn't have to be a C89 type.

我找到了5个候选人:


  • size_t

  • ptrdiff_t

  • intptr_t / uintptr_t

  • int_fast * _t / uint_fast * _t

  • int_least * _t / uint_least * _t

  • size_t
  • ptrdiff_t
  • intptr_t / uintptr_t
  • int_fast*_t / uint_fast*_t
  • int_least*_t / uint_least*_t

有更简单的代码可以更好说明问题。这两个特定循环中 i j 的最佳类型是什么。如果有充分的理由,两种不同的类型也可以。

There is simple code to better illustrate problem. What is the best type for i and j in these two particular loops. If there is a good reason, two different types are fine too.

for (i=0; i<imax; i++) {
        do_something(a[i]);
}
/* jmin can be less than 0 */
for (j=jmin; j<jmax; j++) {
        do_something(a[j]);
}

P.S。
在问题的第一个版本中,我忘记了负面指数。

P.S. In the first version of question I had forgotten about negative indexes.

P.P.S。
我不打算编写C99编译器。但是编译器程序员的任何答案对我来说都是非常有价值的。

P.P.S. I am not going to write a C99 compiler. However any answer from a compiler programmer would be very valuable for me.

类似的问题:

推荐答案

我几乎总是使用 size_t 用于数组索引/循环计数器。当然有一些特殊情况你可能需要签名的偏移,但一般来说使用签名类型有很多问题:

I almost always use size_t for array indices/loop counters. Sure there are some special instances where you may want signed offsets, but in general using a signed type has a lot of problems:

最大的风险是,如果你是调用者将事物视为未签名(或者如果您从错误信任的文件中读取它)传递了一个巨大的大小/偏移量,您可以将其解释为负数并且无法捕获它超出范围。例如 if(offset< size)array [offset] = foo; else error(); 将写入不应该写的地方。

The biggest risk is that if you're passed a huge size/offset by a caller treating things as unsigned (or if you read it from a wrongly-trusted file), you may interpret it as a negative number and fail to catch that it's out of bounds. For instance if (offset<size) array[offset]=foo; else error(); will write somewhere it shouldn't.

另一个问题是带有符号整数溢出的未定义行为的可能性。无论你使用无符号算术还是有符号算术,都需要注意和检查溢出问题,但我个人觉得无符号行为更易于处理。

Another problem is the possibility of undefined behavior with signed integer overflow. Whether you use unsigned or signed arithmetic, there are overflow issues to be aware of and check for, but personally I find the unsigned behavior a lot easier to deal with.

然而使用无符号算术的另一个原因(通常) - 有时我使用索引作为位数组的偏移量,我想使用%8和/ 8或%32和/ 32。对于签名类型,这些将是实际的除法操作。使用无符号时,可以生成预期的按位和/位移操作。

Yet another reason to use unsigned arithmetic (in general) - sometimes I'm using indices as offsets into a bit array and I want to use %8 and /8 or %32 and /32. With signed types, these will be actual division operations. With unsigned, the expected bitwise-and/bitshift operations can be generated.

这篇关于C中数组索引的正确类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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