Questions tagged [control-flow]

Control flow (or flow of control) refers to the order in which statements are evaluated or executed.

Control flow (or flow of control) refers to the order in which statements are evaluated or executed.

There are many methods to control the flow of execution in a program:

Unconditional jumps can use labels:

foo:
printf ("Hello, world.\n");
goto foo;

... or line numbers:

10 PRINT "something"
20 GOTO 10

Conditional branching can use constructs:

if ($x > 3) {
    print "$x is many.";
} else {
    print "$x is few.";
}

... or statements:

case n of
    1 : writeln('one');
    2 : writeln('two');
    3 : writeln('three');
end;

Loops of various kinds exist, including loops:

for (var i = 0; i < 9; i++) {
    window.alert(i);
}

... loops:

foreach (int x in myArray)
{
    Console.WriteLine(x);
}

... and loops:

while read z
do
    echo "Hello, ${z}."
done

Loops can also be terminated early, or made to bypass some of the loop body, with and statements respectively:

for club in ("groucho", "fight", "fight", "kitkat", "drones"):
    if club == "fight":
        continue
    if club == "kitkat":
        break
    print(club)

Functions temporarily divert execution to named sections of code, before returning:

hello = (name) -> "Hello, #{ name }."
console.log hello "world"

Exceptions are used to divert control flow in exceptional circumstances:

try {
    x = 1 / 0;
    System.out.println("Hello, world."); // is not reached
} catch (ArithmeticException e) {
    System.out.println("Goodbye, world.");
} 
837 questions
713
votes
39 answers

How can I break out of multiple loops?

Given the following code (that doesn't work): while True: # Snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok.lower() == "y": break 2 # This doesn't work :( if ok.lower() == "n":…
Matthew Scharley
  • 127,823
  • 52
  • 194
  • 222
276
votes
51 answers

How to avoid "if" chains?

Assuming I have this pseudo-code: bool conditionA = executeStepA(); if (conditionA){ bool conditionB = executeStepB(); if (conditionB){ bool conditionC = executeStepC(); if (conditionC){ ... } …
ABCplus
  • 3,981
  • 3
  • 27
  • 43
200
votes
11 answers

Swift: guard let vs if let

I have been reading about Optionals in Swift, and I have seen examples where if let is used to check if an Optional holds a value, and in case it does – do something with the unwrapped value. However, I have seen that in Swift 2.0 the keyword guard…
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
151
votes
15 answers

How to exit an if clause

What sorts of methods exist for prematurely exiting an if clause? There are times when I'm writing code and want to put a break statement inside of an if clause, only to remember that those can only be used for loops. Lets take the following code…
Roman
  • 3,050
  • 3
  • 21
  • 20
83
votes
7 answers

SQL Server 2000: How to exit a stored procedure?

How can I exit in the middle of a stored procedure? I have a stored procedure where I want to bail out early (while trying to debug it). I've tried calling RETURN and RAISERROR, and the sp keeps on running: CREATE PROCEDURE dbo.Archive_Session…
Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
68
votes
28 answers

Why use a for loop instead of a while loop?

Possible Duplicates: Iterate with for loop or while loop? Loops in C - for() or while() - which is BEST? When should one use a for loop instead of a while loop? I think the following loops are identical, except for their syntax. If so, then why…
Ziggy
  • 21,845
  • 28
  • 75
  • 104
47
votes
8 answers

Python: avoiding if condition for this code?

for the following code a =func() if a != None: b.append(a) a can be assigned to None, is there a way to avoid the if statement and only use one line of code? original problem is the following import xml.etree.ElementTree as etree r =…
Jerry Gao
  • 1,389
  • 3
  • 13
  • 17
47
votes
6 answers

How to determine if an exception was raised once you're in the finally block?

Is it possible to tell if there was an exception once you're in the finally clause? Something like: try: funky code finally: if ???: print('the funky code raised') I'm looking to make something like this more DRY: try: funky…
wim
  • 338,267
  • 99
  • 616
  • 750
34
votes
3 answers

Why does non-equality check of one variable against many values always return true?

I have a variable v in my program, and it may take any value from the set of values "a", "b", "c", ..., "z" And my goal is to execute some statement only when v is not "x", "y", or "z". I have tried, for C-like languages (where equality operators…
33
votes
1 answer

How to implement a do-while loop in tsql

I'm trying to figure how to implement this in TSQL do update stuff set col = 'blah' where that_row = 'the right one' select trash from stuff ... until some_condition The only iterative control flow sentence provided by Transact-SQL is while…
Rodrigo
  • 4,365
  • 3
  • 31
  • 49
31
votes
12 answers

Programming style: should you return early if a guard condition is not satisfied?

One thing I've sometimes wondered is which is the better style out of the two shown below (if any)? Is it better to return immediately if a guard condition hasn't been satisfied, or should you only do the other stuff if the guard condition is…
John Topley
  • 113,588
  • 46
  • 195
  • 237
29
votes
7 answers

Perl Breaking out of an If statement

This one just came up: How do I break out of an if statement? I have a long if statement, but there is one situation where I can break out of it early on. In a loop I can do this: while (something ) { last if $some_condition; blah, blah,…
David W.
  • 105,218
  • 39
  • 216
  • 337
25
votes
2 answers

Is non-local return in Scala new?

A colleague just showed me this and I was surprised that it compiled at all: def toUpper(s: Option[String]): String = { s.getOrElse(return "default").toUpperCase // ^^^^^^ // a return here in the closure?? } and this even…
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
24
votes
8 answers

Are there any static Call-Graph and/or Control-Flow-Graph API for JavaScript?

Are there any Call-Graph and/or Control-Flow-Graph generators for JavaScript? Call Graph - http://en.wikipedia.org/wiki/Call_graph Control Flow Graph - http://en.wikipedia.org/wiki/Control_flow_graph EDIT: I am looking specifically for a static tool…
DuduAlul
  • 6,313
  • 7
  • 39
  • 63
24
votes
2 answers

How do I break an outer loop from an inner one in Perl?

Suppose I have a piece of Perl code like: foreach my $x (@x) { foreach my $y (@z) { foreach my $z (@z) { if (something()) { # I want to break free! } # do stuff } # do stuff } # do stuff } If something() is true, I would like…
David B
  • 29,258
  • 50
  • 133
  • 186
1
2 3
55 56