数组下标索引的循环原来可以这样写

一般我会这样写:

 1 #include "stdafx.h"
 2 #include <Windows.h>
 3 
 4 int _tmain(int argc, _TCHAR* argv[])
 5 {
 6     int arr[]={100,101,102,103,104,105,106,107,108,109};
 7     int count=sizeof(arr)/sizeof(int);
 8     int index=0;
 9 
10     ///////////////////////////here/////////////////////////////////////////
11     for (; index<count; index++)
12     {
13         printf("arr[%d]=%d
", index, arr[index]);
14         Sleep(900);
15         if(index+1==count)
16             index=-1;
17     }
18     //////////////////////////////////////////////////////////////////////////
19 
20     getchar();
21     return 0;
22 }

今天看了live555的函数:void BasicTaskScheduler::SingleStep(unsigned maxDelayTime),发现了新的非常简洁的写法:

 1 #include "stdafx.h"
 2 #include <Windows.h>
 3 
 4 int _tmain(int argc, _TCHAR* argv[])
 5 {
 6     int arr[]={100,101,102,103,104,105,106,107,108,109};
 7     int count=sizeof(arr)/sizeof(int);
 8     int index=0;
 9 
10     ///////////////////////////////here/////////////////////////////////////
11     do 
12     {
13         printf("arr[%d]=%d
", index, arr[index]);
14         index=(index+1) % count;
15         Sleep(900);
16     } while (true);
17     //////////////////////////////////////////////////////////////////////////
18 
19     getchar();
20     return 0;
21 }

对比可知,第一个种写法,要在两个地方控制index变量(第11行,第15到第16行);而第二种写法,只需要在一个地方用一行代码(第14行),就能控制index变量。

完。

原文地址:https://www.cnblogs.com/liyou-blog/p/4211654.html