Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

How to Port Goto Code to Java

Name: Anonymous 2014-02-09 16:44

Lets see how we can replace an ugly goto with an elegant structured programming constructs.

Given an unstructured loop

line1:
printf("Dijkstra sucks cocks in hell.\n");
goto line1;


Without sacrificing any expressiveness, we can refactor the above code into:

line = 0;
while (line++ > 0)
{
switch(line)
{
case 1: printf("Dijkstra sucks cocks in hell.\n") break;
case 2: line = 1; break;
}
}


Not only did we killed goto, but also gained a way to address lines of code dynamically. I.e. we can compute the next value of "line" variable.

Name: Anonymous 2014-02-11 17:52

This is awesome!

bad

int password_correct = 0;
char big_enough_buffer[10];
do {
puts("enter password to continue");
gets(big_enough_buffer)
if (strcmp(big_enough_buffer, PASSWORD) == 0)
password_correct = 1
} while(!password_correct)


good

int line = 0;
int password_correct;
char big_enough_buf[10];
while (line++ < 200) {
switch (line) {
case 20: password_correct = 0; break;
case 30: puts("enter password to continue"); break;
case 40: gets(big_enough_buffer); break;
case 50: if (strcmp(big_enough_buffer, PASSWORD) != 0) line = 69; break;
case 60: password_correct = 1; break;
case 70: if (!password_correct) line = 29; break;
}
}


Oh boy! I've got an idea that might improve this! Check this out:


#define PROGRAM(CODE) \
int line = 0; \
while (line < 999999) { \
switch (line) { \
CODE \
} \
line++; \
}
#define LINE case
#define GOTO(LINE) line = (LINE-1);
#define ENDLINE ;break;


Pretty awesome, I know =)

To make things even more clear:

#defin DO :
#define PLEASE /* just to be polite */


Now we can do our above code like this:


int password_correct;
char big_enough_buf[10];
CODE(
LINE 10 PLEASE DO password_correct = 0 ENDLINE
LINE 20 PLEASE DO puts("enter password to continue") ENDLINE
LINE 30 PLEASE DO gets(big_enough_buffer) ENDLINE
LINE 40 PLEASE DO if (strcmp(big_enough_buffer, PASSWORD) != 0) GOTO(60) ENDLINE
LINE 50 PLEASE DO password_correct = 1 ENDLINE
LINE 60 PLEASE DO if (!password_correct) GOTO(20) ENDLINE


And all this clearness with no goto at all =)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List