此代码中do-while的含义

Nar*_*rek 1 c++ cocos2d-x nextpeer

Nextpeer教程中,您可以看到这样的代码:

CCScene* GameLayer::scene() {
    CCScene * scene = NULL;
    do {
        // 'scene' is an autorelease object
        scene = CCScene::create();
        CC_BREAK_IF(! scene);

        // 'layer' is an autorelease object
        GameLayer *layer = GameLayer::create();
        CC_BREAK_IF(! layer);

        // add layer as a child to scene
        scene->addChild(layer);
    } while (0);

    // return the scene
    return scene;
}
Run Code Online (Sandbox Code Playgroud)

do-while这段代码中block 的含义是什么?

Rad*_*def 5

CC_BREAK_IF是一个宏if(condition) break.(编辑:我已经确认它是.)

这是用于结构化goto的习语:

do {
    if (!condition0) break;
    action0();
    if (!condition1) break;
    action1();
} while(0);
Run Code Online (Sandbox Code Playgroud)

do...while(0); 存在只是为了允许break语句跳过某些代码段.

这类似于:

if (!condition0) goto end;
action0();
if (!condition1) goto end;
action1();
end:
Run Code Online (Sandbox Code Playgroud)

除了它避免使用goto.

使用这些习语中的任何一个都是为了避免嵌套if:

if (condition0) {
    action0();
    if (condition1) {
        action1();
    }
}
Run Code Online (Sandbox Code Playgroud)