continue在while和for里的区别

#include <stdio.h>

int main(void)
{
	int count = 0;
	char ch;
	
	while (count < 10)
	{
		ch=getchar();
		if (ch == '\n')
			continue;
		putchar(ch);
		count++; 
	}
	printf("\ncount is %d.\n",count);
	
	return 0;
 } 

在while循环里,直接跳过了余下的语句,包括其中的count++,运行得到结果,其中计数不包括换行符('\n')

#include <stdio.h>

int main(void)
{
	int count = 0;
	char ch;
	
	for(;count<10;count++)
	{
		ch = getchar();
		if (ch == '\n')
			continue;
		putchar(ch);
	}
	printf("\ncount is %d.\n",count);
	
	return 0;
 } 

而在for循环里,continue之后直接跳过了余下语句,转到更新表达式,即对count++求值,在运行时,计数将换行符计入进去了,因此导致运行后比while循环少一个字母。

运行如下:

猜你喜欢

转载自blog.csdn.net/o707191418/article/details/81221168
今日推荐