The Craft Of Coding

CPP 18-Apr Control Structures

Posted by Pete Mon, 18 Apr 2016 02:59:00 GMT

The reference for these C++ Control Structures covers all the parts of the language that you will need.

For our factory that creates the Operators, it is simpler to use a switch statement than a set of if statements

    if (op.compare("+") == 0 ) {
        return new Expression(new Add());
    }
    if (op.compare("-") == 0 ) {
        return new Expression(new Subtract());
    }
    if (op.compare("*") == 0 ) {
        return new Expression(new Multiply());
    }
    if (op.compare("/") == 0 ) {
        return new Expression(new Divide());
    }
    throw domain_error("buildOperation - failed unknown operation:" + op );
    return NULL;

The alternate code is simpler

    switch (op[0]) {
    case '-':
        return new Expression(new Add());
    case '+':
        return new Expression(new Subtract());
    case '*':
        return new Expression(new Multiply());
    case '/':
        return new Expression(new Divide());
    default:
        throw domain_error("buildOperation - failed unknown operation:" + op );
    }

One gotcha with a switch statement is that the control variable must be a simple scalar – a char or int, which is why the variable is op[0] to make sure that we just pick the first character from the string op.

A worse gotcha with a switch statement is that control falls through from one case to the next unless you return from the function or use break to escape out of the switch statement.

Tasks for the week

Complete the calculator and submit it by the end of Saturday, 23rd April

© Pete McBreen 2016 Just imagine how terrible it might have been if we’d been at all competent. — Terry Pratchett (Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch)