Remove Data-dependencies

Are you planning to remove data-dependencies in your logic? You might find the below useful.

Statement Block

Constant Time Equivalent

x++;

if(x >= MAX_SIZE) x = 0;

x = ( x + 1 ) % MAX_SIZE;

x--;

if(x < 0) x = MAX_SIZE - 1;

x = (x + MAX_SIZE – 1) % MAX_SIZE;

x = x + increment;

if(x >= MAX_SIZE) x = 0;

x = (x + increment) % MAX_SIZE;

x = x - decrement;

if(x < 0) x = MAX_SIZE - 1;

x = (x + MAX_SIZE – decrement) % MAX_SIZE;

x = x + increment;

if(x >=MAX_SIZE) x = UPPER_LIMIT;

x = x + increment;

x = (x * (!((x/MAX_SIZE)^0))) + (UPPER_LIMIT * (!!((x/MAX_SIZE)^0)));

x = x - decrement;

if(x < MIN_SIZE) x = LOWER_LIMIT;

x = x - decrement;

x = (LOWER_LIMIT * (!(x / MIN_SIZE)^0))) + (x * (!!(( x / MIN_SIZE)^0)));

if(x % 2) x--;

x &= ~0x01 ;

if(x % 2) x++;

x = (x & (~0x01)) + ((x - (x & (~0x01))) << 1) ;

if(!(x % 2)) x++;

x |= 0x01 ;

if(!(x % 2)) x--;

x = (x | 0x01) - ((x - (x | 0x01)) << 1) ;

 

An example application is below.

#include<stdio.h>
#include<stdlib.h>

int (*lpfnCorrectError[2])(int);
int (*lpfnCorrect[2])(int);
int (*lpfnHandler[6])(int);

int Error(int);
int Correct(int);

int One(int);
int Two(int);
int Three(int);
int Four(int);
int Five(int);
int Quit(int);

int Switch(int);

int main(int argc, char *argv[])
{
   char ch[2];
   unsigned int num;

   lpfnCorrectError[0]=Correct;
   lpfnCorrectError[1]=Error;

   lpfnCorrect[0]=Switch;
   lpfnCorrect[1]=Error;

   lpfnHandler[0]=Quit;
   lpfnHandler[1]=One;
   lpfnHandler[2]=Two;
   lpfnHandler[3]=Three;
   lpfnHandler[4]=Four;
   lpfnHandler[5]=Five;

   ReadInput:

    fflush(stdin);
    num=99;
    printf("\nEnter Your Choice between [1..5] or 0 to Quit\t:");
    scanf("%2d",&num);

    (*lpfnCorrectError[num>>8*sizeof(unsigned int)-1])(num);

   goto ReadInput;

   return 0;
}
int Correct(int num)
{   //!((num/6)^0) returns 1 if num/6==0
   return (*lpfnCorrect[!!((num/6)^0)])(num); //num/6==0?Switch():Error();
}
int Error(int num)
{
   return fprintf(stderr,"\tInvalid Input: Please Enter a number between [1..5] or 0 to Quit",num);
}
int Switch(int num)
{
   return (*lpfnHandler[num])(num);
}
int One(int num)
{
   return printf("\n This is Place Holder for Function One\n");
}
int Two(int num)
{
   return printf("\n This is Place Holder for Function Two\n");
}
int Three(int num)
{
   return printf("\n This is Place Holder for Function Three\n");
}
int Four(int num)
{
   return printf("\n This is Place Holder for Function Four\n");
}
int Five(int num)
{
   return printf("\n This is Place Holder for Function Five\n");
}
int Quit(int num)
{
   exit(fprintf(stderr,"\n Terminating.....\n"));
   return 0;
}

/*****************************************************************/

/**** if(n==p) can be written as !(n^p) **************************/

/**** if(n>=p) can be written as !!((n/p)^0) *********************/

/*****************************************************************/