for和while的几种用法

本文最后更新于:2022年3月19日 凌晨

三段式for循环#

// 变量声明在for里面,自增在里面
for (int i = 0; i < 10; ++i)
{
	//...
}
// 变量声明在外面,自增在里面
int i = 0;
for (; i < 10; )
{
	//...
	++i;
}
bool condition = true;
int i = 0;
for (; condition; )
{
	//...
	++i;
	if (!(i < 5))
		condition = false;
}

无限循环版本

bool condition = true;
int i = 0;
for (; ; )
{
	//...
	++i;
	if (!(i < 5))
		condition = false;
}

范围for循环#

std::vector<int> l{1,2,3,4,5,6,7,8,9};
for (const auto& it : l)
{
	std::cout << it << std::endl;
}

while#

普通条件while,循环五次退出while

int i = 0;
do {
	++i;
} while ( i < 5 )

循环一次推出while

do {

} while ( false )

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!