Skip to content

Latest commit

 

History

History
60 lines (45 loc) · 2.64 KB

c5.md

File metadata and controls

60 lines (45 loc) · 2.64 KB

Chapter 5: Jumping around with goto

It's time for getting into some pretty important stuff when it comes to programming: (conditional) jumps! With these jumps you can create complex programs with sub-processes and the like - more about goto and it's use cases in this chapter!

What is goto?

History time!
The goto expression is a relic of the past - while many languages still support the use of it, you almost never see it in modern code. It is an unconditional jump, meaning it will jump to a given line-index or label in the code regardless of environment - unconditional meaning that it always executes whenever it is called, no exceptions.

Why is it not used in today's code?
While it does seem to be quite handy when wanting to skip over code it results in a phenomenon commonly known as spaghetti code. This spaghetti code would be littered with goto-calls to a point where the reader of the source code wouldn't know what's going on anymore. To avoid writing code that drives people insane they agreed on using goto to be bad practise.

As much as I bashed on goto now, it's still mandatory in YOLOL as it comes without loops or the like - we'll have to write them ourselves!

Finite and infinite loops

If you have some programming knowledge you probably came across for or while couple of times. They are so called loops, as they repeat the block of instructions inside of them a given amount of times. A small example from JavaScript:

for (let i = 0; i < 10; i++) {
    console.log(`Iteration: ${i}`);
}

For those who never came in contact with such code before:
In this case i keeps track of which iteration (or "repetition") we are on. We start at the count of zero and work our way up to a number which is smaller than 10. For each iteration this code will then print something to our console.
Simple, right? In YOLOL we don't have this kind of syntax nor the keywords for and while, so we'll have to make them ourselves!

Infinite loops

In order to achieve a loop in YOLOL we'll have to use goto.

Step #1:
Try running the following snippet and see how goto works!

######SNIPPET i+=1 goto 1

What this code will do is initializing a variable called i and increase it by one each time the line is executed. The goto will make the program jump back into line 1, thus the variable will be increased until an overflow-error forces the program to terminate. And with this, we have our first infinite loop!

But what if we want to increase i only up to a specific value - let's say 50?
Find out more in the next chapter!

Previous Chapter Next Chapter