Question

The GNU C Extensions provide a specification of label declarations, so that labels can be assigned to variables which can be used by gotos. While I acknowledge that goto makes sense in certain situations (e.g. as a substitute for exception handling in higher languages), I do not understand how this goto language extension could be justified. Can you provide a concrete example, where label values provide benefits?

Was it helpful?

Solution

The one time I used it to good effect was for threaded dispatch. Imagine an interpreter's inner loop:

while (1) {
  switch ( *instruction_pointer ) {
    case INSTR_A:
      ...
      break;
    case INSTR_B:
      ...
      break;
    ...
  }
  ++instruction_pointer;
}

The biggest performance problem with the looping construct itself is that there's one branch (ideally) in that swtich statement which is handling all instructions. That branch can never be properly predicted. With threaded dispatch you add explicit code to every case to go to the next:

void *instructions[] = { &&instr_a, &&instr_b, ... };
...
  goto *instructions[*instruction_pointer];

  instr_a:
    ...
    goto *instructions[*++instruction_pointer];

  instr_b:
    ...
    goto *instructions[*++instruction_pointer];

Each instruction is able to jump directly to the start of the next instruction. Common sequences of instructions are faster due to CPU branch prediction. And it guarantees a jump table implementation, where the switch might not work out that way if the instruction space is slightly sparse.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top