Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the C preprocessor to effectively rename variables

I'm writing a few very tight loops and the outermost loop will run for over a month. It's my understanding that the less local variables a function has, the better the compiler can optimize it. In one of the loops, I need a few flags, only one of which is used at a time. If you were the proverbial homicidal maniac that knows where I live, would you rather have the flag named flag and used as such throughout or would you prefer something like

unsigned int flag;

while (condition) {

#define found_flag flag
  found_flag = 0;
  for (i = 0; i<n; i++) {
    if (found_condition) {
      found_flag = 1;
      break;
    }      
  }
  if (!found_flag) {
     /* not found action */
  }

/* other code leading up to the next loop with flag */
#define next_flag flag
  next_flag = 0;
/* ... /*  
}

This provides the benefit of allowing descriptive names for each flag without adding a new variable but seems a little unorthodox. I'm a new C programmer so I'm not sure what to do here.

like image 826
aaronasterling Avatar asked Nov 30 '22 10:11

aaronasterling


1 Answers

Don't bother doing this, just use a new variable for each flag. The compiler will be able to determine where each one is first and last used and optimise the actual amount of space used accordingly. If none of the usage of the flag variables overlap, then the compiler may end up using the same space for all flag variables anyway.

Code for readability first and foremost.

like image 161
dreamlax Avatar answered Dec 10 '22 14:12

dreamlax