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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With