Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is variable defined by const int determined at compilation time?

Tags:

c++

I'm just wondering whether sentences like const int N=10 will be executed at compilation time. The reason I'm asking is because that the following code will work.

int main()
{
  const int N=10;
  int a[N]={};
  return 0;
}    

But this one wouldn't.

int main()
{
  int N=10;
  int a[N]={};
  return 0;
}
like image 574
andy90 Avatar asked Nov 20 '14 19:11

andy90


1 Answers

The compiler must generate code "as if" the expression was evaluated at compile time, but the const itself isn't sufficient for this. In order to be used as the dimension of an array, for example, expression N must be a "constant integral expression". A const int is a constant integral expresion only if it is initialized with a constant integral expression, and the initialization is visible to the compiler. (Something like extern int const N;, for example, can't be used in a constant integral expression.)

To be a constant integral expression, however, the variable must be const; in your second example, the behavior of the compiler and the resulting program must be "as if" the expression were only evaluated at runtime (which means that it cannot be used as the dimension of an array). In practice, at least with optimization, the compiler likely would evaluate N at compile time, but it still has to pretend it can't, and refuse to compile the code.

like image 103
James Kanze Avatar answered Oct 05 '22 02:10

James Kanze