Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c - What's the best way to do a reverse 'for' loop with an unsigned index?

My first attempt of reverse for loop that does something n times was something like:

for ( unsigned int i = n-1; i >= 0; i-- ) {
    ...     
}

This fails because in unsigned arithmetic i is guaranteed to be always greater or equal than zero, hence the loop condition will always be true. Fortunately, gcc compiler warned me about a 'pointless comparison' before I had to wonder why the loop was executing infinitely.


I'm looking for an elegant way of resolving this issue keeping in mind that:

  1. It should be a backwards for loop.
  2. The loop index should be unsigned.
  3. n is unsigned constant.
  4. It should not be based on the 'obscure' ring arithmetics of unsigned integers.

Any ideas? Thanks :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How about:

for (unsigned i = n ; i-- > 0 ; )
{
  // do stuff with i
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...