gpt4 book ai didi

conditional-statements - 哪个是循环中的首选条件?

转载 作者:行者123 更新时间:2023-12-03 23:17:36 24 4
gpt4 key购买 nike

int n = 5;
for(int i = 0;i!=n;i++)//condition !=
{
//executing 5times
}

int n = 5;
for(int i = 0;i<n;i++)//condition <
{
//executing 5times

}

哪一个是首选?

This was example from "Accelerated C++ : practical programming by example / Andrew Koenig, Barbara E. Moo." Just wanted to know why the Author prefers the first one

最佳答案

第二。有两个原因

  • 小于(或有时 <=)是大多数编码器编写这些的通常方式,如果可能的话,最好坚持约定 - != 可能会让大多数编码器检查两次以检查循环中是否有一些奇怪的东西,而< 将立即被理解。
  • != 取决于确切的条件。如果在维护期间修改了循环的内部并且我不小心在循环内增加了那么你最终会得到一个无限循环。一般来说,让你的终止条件尽可能宽总是更好 - 它只是更健壮。

  • 2当然是1的原因。

    关于conditional-statements - 哪个是循环中的首选条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/477468/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com