型号为C99数组索引 [英] Type for array index in C99

查看:90
本文介绍了型号为C99数组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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名候选人:

I have found 5 candidates:


  • 为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

有简单code,以更好地说明问题。什么是 I Ĵ这两个特殊的循环最好的类型。如果有一个很好的理由,两种不同类型的都很好了。

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:

最大的风险是,如果你通过了一项规模庞大/由主叫方处理事情的无符号偏移量(或者,如果你从错误地信任的文件中读取),您可跨preT它作为一个负数量和不能赶上它的出界。例如如果(偏移&LT;大小)阵列[抵销] = foo的;其他错误(); 将某处写它不应该

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。有符号的类型,这些都将是实际的除法运算。无符号,可以产生预期的按位和/ bitshift操作。

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.

这篇关于型号为C99数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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