How computers 'think', or conditional instruction 'if' explained.

Computers do not think, they compute (count expression values).

Let's see how processor instruction with assembler mnemonic jne (jump if not equal) may work.


101. jne val1 val2 :my_section
102. ...
103. ...
104. ...
105. ...


:my_section: 205. ...

above code is easy to explain:

1. At line 101, jne compares val1 with val2. if they are equal, it continues without jump (at line 102).
2. If val1 is not equal with val2, then jne jumps to memory address to which :my_section label points (line 205).

How it works?

This 'magic' of conditional instruction is explained with few simple tricks:

1. compute eq.

eq = (val1 - val2 == 0) (this is logical expression with boolean value, which in low level evaluates to 0 for false, or 1 for true).

2. next part-instruction for jne is addition.

result of (eq + 1) is added to instruction pointer register, that is either 0 for false or 1 for truth.

3. processor continues with next instruction, as pointed by instruction pointer register.

4. depending on value added at point 2, we end up jumping to line 102, or to line pointed by :my_section label.

That's it, this is conditional branch. We end up executing different code depending on whether val1 is equal with val2 or not.

P.S. please note that memory address and assembly language line are different things.. but work in similar way.

See also: Conditional Instruction & Expressions.

No comments:

Post a Comment