Is there a speed difference between using const and static const inside a function?

In C, what is the difference between static const

and const

within a function ?

For example, take the given code examples:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int( 1 );
  return 0;
}

      

Versus:

void print_int(int x) {
  assert( x < 5 && x > -5 );
  static const int i[9] = {
    -4, -3, -2, -1, 0, 1, 2, 3, 4
  };
  printf("%i", i[x + 4]);
}
int main() {
  print_int(1);
  return 0;
}

      

Would the optimized generated assembly be better if I used static const

instead const

, or would the output be the same for both examples? Oh, these examples assume all optimizations were turned off, as the compiler could efficiently optimize both results to get the same result.

+3


source to share


1 answer


Would the optimized generated assembly be better if I used static

const

instead const

, or would the output be the same for both examples?

No, the build will not be the same, at least assuming x86 ABI and corresponding ISA. Static storage objects are initialized before the program starts. The auto-hold time objects are managed in a stack frame, which is set per function. They can also be stored directly in CPU registers if the compiler decides to do so.



There will be no significant performance difference between these two examples, since the I / O function is the printf()

most time consuming.

+3


source







All Articles