Search code examples
c++cocos2d-xnextpeer

Meaning of do-while in this code


In the tutorial of Nextpeer you can see such code:

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;
}

What is the meaning of do-while block in this code?


Solution

  • CC_BREAK_IF is a macro for if(condition) break. (Edit: I've confirmed that it is.)

    This is an idiom used for a structured goto:

    do {
        if (!condition0) break;
        action0();
        if (!condition1) break;
        action1();
    } while(0);
    

    do...while(0); exists only to allow a break statement to skip some section of code.

    This would be similar to:

    if (!condition0) goto end;
    action0();
    if (!condition1) goto end;
    action1();
    end:
    

    Except it avoids the use of goto.

    The use of either of these idioms is to avoid a nested if:

    if (condition0) {
        action0();
        if (condition1) {
            action1();
        }
    }