User Tools

Site Tools


guides:programstyle:goto

This is an old revision of the document!


Use of goto/break/continue/return Statements

All of these statements change the flow of control in a c++ program. They change the behavior of control structures and therefore make it more difficult to understand the final flow of control in a program. For these reasons, the use of these statements is heavily restricted.

goto

continue

break

return

Return statements are used to transfer control from a called function to a calling function. In C++ the return statement may or may not return a value, depending on the function prototype.

Local convention states that each function should have exactly one return statement and that this statement should be the last line of code in the function.

Examples of acceptable use:

// note the return for a void function has no argument.
void PrintHello(void) {
    cout << hello << endl;
 
    return;
}
 
int Square(int n) {
    return n*n;
}

A function should not have more than a single return. The following example does not match the style guide:

bool IsPositive(int n) {
    if (n > 0) {
       return true;
    } else {
       return false;
    }
}

For more advanced classes, especially after the student has demonstrated a strong grasp of flow control and logical expressions, the above code *might* be acceptable. In general, multiple returns should only be employed when the code is extremely simple. Speciffically, replacing /break/ statements in a switch structure with returns meets this criteria, as long as *all* break statements are replaced.

string DigitName(int n) {
   string name;
     switch(n) {
      case 1: name = "One";
              break;
      case 2: name = "Two";
              break;
      case 3: name = "Three";
              break;
      ...
 
   } 
   return name;
}
 
string DigitName(int n) {
   switch(n) {
      case 1: return "One";
      case 2: return "Two";
      case 3: return "Three";
      ...
 
   }
   return "";
}

Please consult your instructor before you use more than one return in a function.

guides/programstyle/goto.1596552348.txt.gz · Last modified: 2022/08/02 11:59 (external edit)