How to make this C code shorter -


i have code toggles values in struct.

for example, find myself writing code lot looks this:

if(options.test == 1) {     options.test = 2; } else if (options.test == 2) {     options.test = 1; } 

is there more compact version can use make code shorter?

if values of options.test either 1 or 2 throughout execution of program, can do:

options.test = 3-options.test; 

if variable may set other values, best way handle with:

switch (options.test) {     case 1:   options.test = 2;   break;     case 2:   options.test = 1;   break;     case ...: options.test = ...; break;     case ...: options.test = ...; break;     case ...: options.test = ...; break;     default:  options.test = ...; break; } 

if values between 0 , n (with relatively small n), may consider hashing.

for example, instead of:

switch (options.test) {     case 0: options.test = 4; break;     case 1: options.test = 2; break;     case 2: options.test = 1; break;     case 3: options.test = 3; break;     case 4: options.test = 5; break;     case 5: options.test = 0; break; } 

you can do:

static int hash[] = {4,2,1,3,5,0}; options.test = hash[options.test]; 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -