Fastest way to test if two integers differ by 4 or equal to each other I'm searching for the fastest way to test if two integers are equal or differ by 4. The integers can be positive, negative and equal to zero. They are between -1000 and 1000 and are exclusively multiples of 4.

The simplest approach to test this should be this:

if(x == y || x - y == 4 || x - y == -4)
{
     //do something...
}


But since I want to do this 4 times inside of a interrupt sub routine I wanted to know if there is a faster way to do this.
If you need to do the same comparison 4 times you can just put the result into a boolean variable.

boolean b = (x == y || x - y == 4 || x - y == -4)

if( b )
{
     //do something...
}


If you are talking about optimizing the actual code, I shouldn't worry about it. The compiler is already pretty good at this. Here is the assembler code for it.

void test(int x, int y)
{
    if(x == y || x - y == 4 || x - y == -4)
  a8:   86 17           cp  r24, r22
  aa:   97 07           cpc r25, r23
  ac:   39 f0           breq    .+14        ; 0xbc &lt;_Z4testii+0x14&gt;
  ae:   86 1b           sub r24, r22
  b0:   97 0b           sbc r25, r23
  b2:   84 30           cpi r24, 0x04   ; 4
  b4:   91 05           cpc r25, r1
  b6:   11 f0           breq    .+4         ; 0xbc &lt;_Z4testii+0x14&gt;
  b8:   04 96           adiw    r24, 0x04   ; 4
  ba:   09 f4           brne    .+2         ; 0xbe &lt;_Z4testii+0x16&gt;
    {
        asm ("wdr");
  bc:   a8 95           wdr
  be:   08 95           ret


first it compare the two values x and y. Then is subtract y from x and compares it with 4. After that it gets the subtracted value from the previous step; adds 4; and check if it is 0.

EDIT

As to Dave X's suggestion; using if(abs(x-y)&lt;=4)

void test(int x, int y)
{
    if(abs(x-y)&lt;=4)
  a8:   86 1b           sub r24, r22
  aa:   97 0b           sbc r25, r23
  ac:   04 96           adiw    r24, 0x04   ; 4
  ae:   09 97           sbiw    r24, 0x09   ; 9
  b0:   08 f4           brcc    .+2         ; 0xb4 &lt;_Z4testii+0xc&gt;
    {
         asm("wdr");
  b2:   a8 95           wdr
  b4:   08 95           ret


So half the number of instructions needed. But as Paul said, this might not the fastest. This code always takes 5 instructions, while the previous code will only take 3 instructions if x==y. So if 90% of the time x==y, the previous code will be faster 90% of the time.

As to the assembler code, you can see how clever the compiler is. It first subtracts y from x. Then it adds 4. If -4 &lt;= x-y &lt; 0 the carry bit is set. Then it subtracts 9 (so it's like (x-y)-5 because of the previous +4). If 0&lt;= x-y &lt;= 4 the carry bit is set. It then check if the carry bits is set by either of the last to instructions. Pretty clever.