在C族中,在环中为什么是“小于或等于”更优选超过“小于”符号? [英] In C families, in a loop why is "less than or equal to" more preferred over just "less than" symbol?

查看:150
本文介绍了在C族中,在环中为什么是“小于或等于”更优选超过“小于”符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C语言族中,当我们使用任何循环的计数器时,最优选的比较是 Greater Equal To <= 或其逆?请查看这三个代码

  for(var i = 0; i <= 5; i ++)
{...} /// loop1

for(var i = 0; i <6; i ++)
{...} /// loop2

for(var i = 0; i!= 6; i ++)
{...} /// loop3

我理解为什么循环3应该不鼓励代码中的东西可以分配 i> 5 导致无限循环。但 loop1 loop2 本质上是相同的,而 loop2 更好的性能明智,因为只做了一个比较。因此,为什么 loop1 更受欢迎。

我没有正式的编程培训。我只是拿起C当我需要更好的工具来编程8051而不是使用汇编语言。

解决方案

For循环通常用于遍历数组,而limit是数组的长度。因为数组是从零开始的,所以最后一个有效元素是 length-1 。因此,选择是:

  for(int i = 0; i   

  int i = 0; i <= length-1; i ++)

优选。



我们不使用!= 因为偶尔我们写循环,其中索引按变量步长递增,有时它会跳过限制。因此,使用< 比较更安全,因此这些不会变成无限循环。


Why is it that in C family of languages when we use a counter for any loop the most preferred comparison is Greater Equal To <= or its inverse? Please take a look at these three pieces of code

for (var i = 0; i <= 5; i++)
{...}/// loop1

for (var i = 0; i < 6; i++)
{...}/// loop2

for (var i = 0; i != 6; i++)
{...}/// loop3

I understand why loop 3 should be discouraged as something in code can assign i > 5 causing infinite loop. But loop1 and loop2 are essentially the same and loop2 may be better performance wise since only one comparison is done. So why is loop1 more preferred. Is it just convention or is there something more to it?

Note: I have no formal training in programming. i just picked up C when I needed better tools to program 8051s rather than using assembly language.

解决方案

For loops are often used to iterate over arrays, and the limit is the length of the array. Since arrays are zero-based, the last valid element is length-1. So the choice is between:

for (int i = 0; i < length; i++)

and

for (int i = 0; i <= length-1; i++)

The first is simpler, so it is preferred. As a result, this idiom has become common even when the limit is not an array size.

We don't use != because occasionally we write loops where the index increments by variable steps, and sometimes it will skip over the limit. So it's safer to use a < comparison, so these won't turn into infinite loops.

这篇关于在C族中,在环中为什么是“小于或等于”更优选超过“小于”符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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