为什么 C 和 C++ for 循环使用 int 而不是 unsigned int? [英] Why is int rather than unsigned int used for C and C++ for loops?

查看:52
本文介绍了为什么 C 和 C++ for 循环使用 int 而不是 unsigned int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当愚蠢的问题,但为什么在 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 具有比原始整数类型更可取的语义类型定义.例如,大小"的所有内容都应输入为 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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