条件检查C中的循环 [英] condition check in for loop in C

查看:59
本文介绍了条件检查C中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串"str". 我的for循环如下:

Suppose I have a string "str". My for loop is as follows:

 for(i=0;i<strlen(str);i++){

    //do stuff

 }

问题:检查条件后,i

question: When the condition is checked ,i < strlen(str), is the strlen(str) part calculated each time the loop runs ? Or it gets stored and is computed for the first time only?

推荐答案

循环中的条件表达式将在每次迭代时得到求值-这样(必须)直到(理想情况下)表达式变为假.所以是的:strlen(str)将被一遍又一遍地计算.如果字符串完全不变,则将其长度存储在局部变量中会更好.

The condition expression in a loop will get evaluated at each and every iteration - it has to be that way until (ideally) the expression becomes false. So yes: strlen(str) will be calculated over and over again. If the string doesn't change at all, it'll be better if you store its length in a local variable.

int n = strlen(str);
for (i=0; i<n; i++) {
    // do stuff
}

这也将起作用:

for (i=0; str[i] != '\0'; i++) {
    // do stuff
}

这篇关于条件检查C中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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