我可以只使用 unsigned int 而不是 size_t 吗?

sta*_*std 4 c unsigned size-t

我的印象size_tunsigned int。但是我可以只写unsigned int而不是size_t在我的代码中吗?

Lun*_*din 6

size_t是描述数组和对象大小时使用的最正确的类型。它保证是未签名的,并且据说“足够大”以容纳给定系统的任何对象大小。因此,它比 用于该目的更便于携带unsigned int,实际上在所有普通计算机上都是 16 位或 32 位。

因此,for迭代数组时最规范的循环形式实际上是:

for(size_t i=0; i<sizeof array/sizeof *array; i++)
{
  do_something(array[i]);
}
Run Code Online (Sandbox Code Playgroud)

而不是int i=0;这也许是更常见的,即使在一些C的书可见。

size_t也是sizeof操作符返回的类型。在某些情况下,使用正确的类型可能很重要,例如printf("%u", sizeof obj);是形式上未定义的行为,因此理论上它可能会导致 printf 崩溃或打印出乱码。你必须使用%zufor size_t

很可能size_t恰好是与unsigned longorunsigned long longuint32_toruint64_t虽然完全相同的类型。

  • @JDługosz 当我回答问题时,这最初被标记为 C。如果从那时起这个问题就被破坏了,那不是我的错。 (2认同)

tst*_*isl 5

该类型size_t是一种无符号类型,能够表示sizeof_Alignof运算符的所有可能结果。见https://port70.net/~nsz/c/c11/n1570.html#6.5.3.4p5

Theunsigned int是 ... 的无符号变体int,可以表示从 0 到 65535 的整数。它可能能够表示更大的整数。见https://port70.net/~nsz/c/c11/n1570.html#5.2.4.2.1

它们可能是也可能不是同一类型。在现代 64 位机器上,它们不是。