Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are value equality comparisons executed in a program?

Tags:

comparison

How does the computer execute value equality comparisons? Does it compare the values bit by bit, starting from the smallest bit, and stop once two different bits are encountered? Or does it start from the highest bit? Does it go through all bits regardless of where/when two unlike bits are found?

like image 884
Måns Nilsson Avatar asked Dec 03 '16 12:12

Måns Nilsson


1 Answers

When you write an equality comparison in a higher level language (e.g. c), it will be transformed to intermediary representation and then to the instructions of a particular platform this code will be executed upon. Compiler is free to implement the equality comparison using any of the instructions available on a target architecture. The idea is usually to make it faster.

Different architectures have different instruction sets. Different processors can have varying implementation strategies (again to make things faster), as long as they comply with the spec.

Below are a few examples

x86

CMP command is used to compare two values. Here's an excerpt from Instruction set reference.

Compares the first source operand with the second source operand and sets the status flags in the EFLAGS register according to the results. The comparison is performed by subtracting the second operand from the first operand and then setting the status flags in the same manner as the SUB instruction. When an immediate value is used as an operand, it is sign-extended to the length of the first operand.

This basically means all bits are examined. I guess it was implemented that way to allow non-equality(<,>) comparisons too.

So all bits are examined. In the simplest cases that can be done serially, but can be done faster. See wikibooks on add / subtract blocks.

Add block scheme with carry lookahead

ARM

TEQ command can be used to test two values for equality. Here's an excerpt from the infocenter.arm.com

The TEQ instruction performs a bitwise Exclusive OR operation on the value in Rn and the value of Operand2. This is the same as the EORS instruction, except that it discards the result. Use the TEQ instruction to test if two values are equal without affecting the V or C flags.

Again all bits are examined.

like image 144
Ivan Avatar answered Oct 21 '22 15:10

Ivan