具有现有起始值的C/C ++ for循环 [英] C/C++ for loop with existing start value

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

问题描述

这是C/C ++ for循环:

Here's a C/C++ for loop:

int i;
for (i = myVar; i != someCondition(); i++)
  doSomething();
// i is now myVar plus the number of iterations until someCondition

我最近不得不使用这样的循环.我需要保留i的值,因为我想知道someCondition()的返回值变为true时i是什么.并且i的起始值为myVar,这没有进一步的原因.因此,想要要做的是:

I recently had to use a loop like this. I needed to keep the value of i because I wanted to know what i was when the return value of someCondition() became true. And the start value of i was myVar which had no further reason of existing. So what wanted to do was:

for (myVar; myVar != someCondition(); myVar++)
  doSomething();
// myVar is now myVar + the number of iterations.

这对我来说更有意义.当myVar正是我所需要的时候,我不明白为什么必须使用一个全新的变量.但这不是有效的代码.有没有办法为这种情况创建一个全新的变量?

This made a lot more sense to me. I didn't see why I had to use a whole new variable when myVar was just what I needed. But this is not valid code. Is there a way around creating a whole new variable for this situation?

推荐答案

您需要的是

for( ; myVar != someCondition(); myVar++)
       doSomething();

但是您对以下循环不正确的说法是错误的,

But you statement about the following loop being incorrect is wrong,

for (myVar; myVar != someCondition(); myVar++)
  doSomething();

上面的代码在C语言中也可以正常工作.

The above code will also work fine in C.

这篇关于具有现有起始值的C/C ++ for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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