1: //selection.cpp 2: //C++ code examples illustrating decision-making constructs 4: //How to format a simple if-statement: 5: if (condition) 6: statement; 8: //If "statement" is very short, the following is also permissible: 9: if (condition) statement; 12: //How to format a simple if...else-statement: 13: if (condition) 14: statement1; 15: else 16: statement2; 18: //If both statements are very short, either of the following 19: //is also permissible: 20: if (condition) statement1; else statement2; 22: if (condition) statement1; 23: else statement2; 25: //How to format an if...else-statement with multi-statement bodies: 26: if (condition) 27: { 28: statement1_1; 29: statement1_2; 30: } 31: else 32: { 33: statement2_1; 34: statement2_2; 35: statement2_3; 36: } 38: //How to format a simple nested if-statement 39: if (condition1) 40: statement1; 41: else if (condition2) 42: statement2; 43: else if (condition3) 44: statement3; 45: else 46: statement4; 48: //How to format nested if-statement 49: //with one (or more) multi-statement bodies: 50: if (condition1) 51: statement1; 52: else if (condition2) 53: { 54: statement2_1; 55: statement2_1; 56: } 57: else if (condition3) 58: statement3; 59: else 60: statement4; 62: //How to format a switch-statement: 63: switch (expression) 64: { 65: case LABEL1: 66: statement1; 67: break; 68: case LABEL2: 69: case LABEL3: 70: case LABEL4: 71: statement2; 72: break; 73: case LABEL5: 74: statement3; 75: break; 76: case LABEL6: 77: statement4; 78: break; 79: default: //optional 80: defaultStatement; 81: break; 82: } 83: //Note that a "break;" immediately prior to the closing brace of 84: //a switch is unnecessary, but is recommended as a "best practice". 86: //Also permissible is this format, which saves horizontal whitespace 87: //and is the default in at least some IDEs, such as Visual C++: 88: switch (expression) 89: { 90: case LABEL1: 91: statement1; 92: break; 93: case LABEL2: 94: case LABEL3: 95: case LABEL4: 96: statement2; 97: break; 98: case LABEL5: 99: statement3; 100: break; 101: case LABEL6: 102: statement4; 103: break; 104: default: //optional 105: defaultStatement; 106: break; 107: } 108: //Note that a "break;" immediately prior to the closing brace of 109: //a switch is unnecessary, but is recommended as a "best practice". 111: //How to format a particularly simple switch-statement: 112: switch (expression) 113: { 114: case LABEL1: statement1; break; 115: case LABEL2: statement2; break; 116: case LABEL3: statement3; break; 117: case LABEL4: statement4; break; 118: default: defaultStatement; break; 119: }