问题描述
这是一个相当愚蠢的问题,但为什么在 C 或 C++ 中为数组定义 for 循环时通常使用 int
而不是 unsigned int
?
This is a rather silly question but why is int
commonly used instead of unsigned int
when defining a for loop for an array in C or C++?
for(int i;i<arraySize;i++){}
for(unsigned int i;i<arraySize;i++){}
我认识到在做数组索引以外的事情时使用 int
的好处,以及在使用 C++ 容器时使用迭代器的好处.仅仅是因为在循环数组时无关紧要吗?或者我应该一起避免它并使用不同的类型,例如 size_t
?
I recognize the benefits of using int
when doing something other than array indexing and the benefits of an iterator when using C++ containers. Is it just because it does not matter when looping through an array? Or should I avoid it all together and use a different type such as size_t
?
推荐答案
这是一个更普遍的现象,通常人们没有使用正确的整数类型.现代 C 的语义 typedef 比原始整数类型更可取.例如,大小"的所有内容都应该输入为 size_t
.如果您系统地为应用程序变量使用语义类型,那么这些类型的循环变量也会变得更容易.
This is a more general phenomenon, often people don't use the correct types for their integers. Modern C has semantic typedefs that are much preferable over the primitive integer types. E.g everything that is a "size" should just be typed as size_t
. If you use the semantic types systematically for your application variables, loop variables come much easier with these types, too.
而且我已经看到了一些难以检测的错误,这些错误来自于使用 int
左右.突然在大型矩阵之类的东西上崩溃的代码.只需使用正确的类型正确编码就可以避免这种情况.
And I have seen several bugs that where difficult to detect that came from using int
or so. Code that all of a sudden crashed on large matrixes and stuff like that. Just coding correctly with correct types avoids that.
这篇关于为什么在 C 和 C++ for 循环中使用 int 而不是 unsigned int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!