一个程序看懂C++ switch 执行流程

来源:互联网 发布:实用的app软件 编辑:程序博客网 时间:2024/06/01 09:01

先上代码:

#include <iostream>using namespace std;int main(){    int a = 0,sum = 0;    for (; a <=3;a++)    {        switch (a)        {        default:sum += 4;        case 1:sum += 1;        case 2:sum += 2;        case 3:sum += 3;        }    }    cout << sum;    return 0;}

不问你了,说我YY 的答案:22,
再说说正确答案,看图:
这里写图片描述
接下来分析一下:该语句是先判断所有条件,在执行相应条件后面的语句,switch跳出有两种,遇到该语句的“}”或者遇到break;由于代码中没有break,座椅只能等到“}”了,所以在每一次匹配条件之后继续依次向后执行,如果没有条件匹配成功,则执行default语句。到此,整个执行流程就清楚了,:
(1)a==0:没有匹配语句,首先执行default语句,完成后为遇到“}”,继续执行case 1,case 2,case3,退出;+4+1+2+3
(2)a==1 : 匹配case 1,未退出,继续执行case 2,case 3,退出;+1+2+3
(3)a==2 : 匹配case 2,未退出,继续执行case 3,退出;+2+3
(4)a==3 : 匹配case 3,退出;+3
结果:24
最后总结两点:(1)只有不匹配才会执行default语句;
(2)只有遇到break或者switch的“}”才会退出;

1 0