How do you define “if” for computers?

431 views

I’m not a programmer, how do you get from binary 1s and 0s to “if x occurs complete y” How do you tell the computer to wait for a future input?

In: 2

11 Answers

Anonymous 0 Comments

You’ve got a range of answers here, but there’s a little bit that I don’t think is getting explained well.

Program code’s just a lot of data in memory. Even though in the languages programmers use you can see how things are connected, once it’s in memory all of the instructions are in a line, like a cookbook with no page breaks.

So the code for “if true” is in one place and the code for “if false” is in another place. Meanwhile the CPU has a special number that tells it where the next instruction is in memory.

So when a programmer does an “if x do y” block of code, really what’s happening is a line of code that’s more like, “If this condition is true, move to the line at this memory location, otherwise just move to the next instruction.”

So the way you tell a computer, “Get eggs if we are out, then do laundry” looks something like this in memory:

(1) Store the number of eggs in A.
(2) If A is bigger than 0, go to instruction 6.
(3) Go to the store.
(4) Get eggs.
(5) Return home.
(6) Do laundry.

The code on lines 3, 4, and 5 won’t be run by the CPU if (2) determines there are eggs, so that means the instructions to buy more eggs won’t run. But even if lines 3, 4, and 5 run, line 6 will run. If we want the more complicated, “If we are out of eggs, get more, but if we have eggs do laundry” you end up with:

(1) Store the number of eggs in A.
(2) If A is bigger than 0, go to instruction 7.
(3) Go to the store.
(4) Get eggs.
(5) Return home.
(6) Go to instruction 8.
(7) Do laundry.
(8) <You’re done!>

Note how lines 3 through 6 only run if there are no eggs, line 7 only runs if we have eggs, but line 8 will run no matter what.

You are viewing 1 out of 11 answers, click here to view all answers.