News for hackers. Stuff that matters.
Re:GOTOphobia Considered Harmful (In C) by klyrs on Sunday February 26, 2023 @03:50PM (#34949268)
I dug around a little and found an example [1] on a reddit thread looking for examples of spaghetti code. Most of the examples on the thread were just badly written code. Irreducible spaghetti code tends to be complex state machines that cannot be rendered well in a flat format. People like to flatten those out with a trampoline pattern[2], but that can hinder performance.

Malicious spaghetti involves transformations such as

   for (x = 0; x < 10; x++) {
       for (y = 0; y < 20; y++) {
           printf("%d %d\n", x, y);
       }
   }

   |
   | DRY
   v

   x = 0;
   loop_x_head:
   condition_val = x;
   condition_stop = 10;
   condition_var = 'x';
   goto check_condition;
   loop_x_body:
   y = 0;
   loop_y_head:
   condition_val = y;
   condition_stop = 20;
   condition_var = 'y';
   goto check_condition;
   loop_y_body:
   printf("%d %d\n", x, y);
   increment_val = y;
   condition_stop = 20;
   increment_var = 'y';
   goto increment;
   loop_y_end:
   increment_val = x;
   condition_stop = 10;
   increment_var = 'x';
   goto increment;
   loop_x_end:
   halt;
   increment:
   increment_val++;
   if (increment_var == 'x')
       x = increment_val;
   if (increment_var == 'y')
       y = increment_val;
   condition_val = increment_val;
   condition_var = increment_var;
   check_condition:
   if (condition_val < condition_stop)
       goto pass_condition:
   if (condition_var == 'x')
       goto loop_x_end;
   if (condition_var == 'y')
       goto loop_y_end;
   pass_condition:
   if (condition_var == 'x')
       goto loop_x_body;
   if (condition_var == 'y')
       goto loop_y_body;

[1] http://wigfield.org/RND_HAR.BAS

[2] https://en.wikipedia.org/wiki/Trampoline_(computing)

There are no comments on this comment yet.