1

C语言循环和switch中的break和continue - idealclover

 2 years ago
source link: https://idealclover.top/archives/330/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C 语言循环和 switch 中的 break 和 continue

2018.01.11 | C 与 C++ | 1519 浏览 | 1 赞 | 0 条评论


请注意,本文编写于 1410 天前,最后修改于 931 天前,其中某些信息可能已经过时。

事件的起因是同学甩来的一道题,问程序的输出结果

#include<stdio.h> int main(void){ int i; for(i=1;i<10;i++){ switch (i%3) { case 0: i+=3; break; case 1: i+=4; continue; printf("%d\n",i);

查了一些资料最终也弄明白了这个题,答案是 11。

问题的关键在于循环和 switch 中的 break 和 continue 的不同。在 switch 中是响应 break 但不响应 continue 的,换句话说,在 switch 中使用 break,break 是针对 switch 的;而在 switch 中使用 continue,continue 是针对 for 的。

具体到这道题来说,第一次循环所响应的是 case 1,i 变成 5 后直接 continue,i 自增为 6 后继续循环;此时响应的是 case 0,i 自增为 9 后 break 出 switch,执行接下来的语句 i++,自增为 10;之后在下一次 for 循环开始时自增为 11,不满足 i<10 条件,跳出 for 循环。最终输出的 i 值即为 11。

参考资料:

http://blog.csdn.net/lvyuan30276/article/details/9383221

本文链接:https://idealclover.top/archives/330/

本作品由 idealclover 采用 知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议 进行许可,转载请注明出处。

标签: void, 共享


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK