0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

for() の代わりにwhileを使える部分

Last updated at Posted at 2025-02-20

最近知ったものです。
初心者の方は参考になるかも!

int limit = ?;
for(int i=0; i<limit; i++){
    ~~~;
}

の代わりに、

while(limit-- >= 0){
    ~~~;
}

が使えるという話!

ただし反復する回数は等しいが、前者のiは1ずつ増えるのに対し、
後者はlimitが1ずつ減るという違いがある。

後者のやり方で1ずつ増やそうとすると、

int limit = ?;
while(limit > i++){
    ~~~;
}

となり、結局iを使うことになるので、forの方がiのスコープが狭くなって使いやすいと思います。スコープが狭いということは、他の部分でiが使えるということなので。

結論、繰り返し処理を行うだけでいいならwhileを使った方がすっきりする

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?