Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Some people will object to this, but I think in these situations a plain old <code>goto</code> is a very clean and readable way of doing things, because it emphasizes the linearity of the "normal" control path:</p> <pre><code>int main(int arg, char *argv[]) { int choice; choose_shape: printf("Choose a shape from the following:\n" " 1.Sphere\n 2.Cone\n 3.Cylinder\n"); scanf("%d", &amp;choice); if (choice &lt; 1 || choice &gt; 3) { printf("Invalid selection, please choose again.\n"); goto choose_shape; } printf("Enter the radius, r:\n"); ... } </code></pre> <p>Yes, people have complained about <code>goto</code> so let me justify it some more.</p> <p>Here is a more sophisticated version that allows you to select a shape by letter:</p> <pre><code> char c; shape_t shape; choose_shape: printf("Choose a shape: [s]phere, [c]one, c[y]linder:\n"); scanf("%c", &amp;c); switch (c) { cases 's': shape = SHAPE_SPHERE; break; case 'c': shape = SHAPE_CONE; break; case 'y': shape = SHAPE_CYLINDER; break; default: printf("Not a valid shape: %c\n", c); goto choose_shape; } </code></pre> <p>And here is the version with <code>goto</code>. Note that this introduces another variable, <code>flag</code>, whose only purpose is to get rid of the <code>goto</code> statement. You cannot simply use <code>break</code> here (which is an unlabeled <code>goto</code> to begin with) because of the <code>switch</code> statement. I consider this harder to read due to the additional state. It's five lines longer.</p> <pre><code> char c; shape_t shape; int flag; for (flag = 0; !flag; ) { printf("Choose a shape: [s]phere, [c]one, c[y]linder:\n"); scanf("%c", &amp;c); switch (c) { cases 's': shape = SHAPE_SPHERE; flag = 1; break; case 'c': shape = SHAPE_CONE; flag = 1; break; case 'y': shape = SHAPE_CYLINDER; flag = 1; break; default: printf("Not a valid shape: %c\n", c); break; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload