一、break和return在多层for循环中的作用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aa375809600/article/details/49000839

break和return在多层for循环中的作用

#include <stdio.h>
#include <vector>
#include <stdlib.h>
using namespace std;
//测试break
void testBreak(){

    printf("%s\n","break=======begin" );
    int count = 10 ;
    for (int i = 0; i < count; ++i)
    {
        for (int j = 0; j < count; ++j)
        {
            printf("j=%d\n", j);

            break;//
        }
        printf("i=%d\n", i);
    }
    printf("%s\n","break=======end" );
}
//用break退出多个循环
void testMulBreak(){

    printf("%s\n","MulBreak=======begin" );
    int count = 10 ;
    for (int i = 0; i < count; ++i)
    {

        for (int j = 0; j < count; ++j)
        {
            printf("j=%d\n", j);

            break;//
        }
        break;
        printf("i=%d\n", i);
    }
    printf("%s\n","MulBreak=======end" );
}
//测试return 
void testReturn(){
    printf("%s\n","return=======begin" );
    int count = 10 ;
    for (int i = 0; i < count; ++i)
    {
        for (int j = 0; j < count; ++j)
        {
            printf("j=%d\n", j);
            return;//整个方法停止
        }
        printf("i=%d\n", i);
    }
    printf("%s\n","return=======end" );
}
int main(int argc, char const *argv[])
{
    testBreak();
    testReturn();
    testMulBreak();
    return 0;
}

运行结果

break=======begin
j=0
i=0
j=0
i=1
j=0
i=2
j=0
i=3
j=0
i=4
j=0
i=5
j=0
i=6
j=0
i=7
j=0
i=8
j=0
i=9
break=======end
return=======begin
j=0
MulBreak=======begin
j=0
MulBreak=======end
[Finished in 0.2s]

没有更多推荐了,返回首页