Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The const modifier in C

Tags:

c

I'm quite often confused when coming back to C by the inability to create an array using the following initialisation pattern...

const int SOME_ARRAY_SIZE = 6;
const int myArray[SOME_ARRAY_SIZE];

My understanding of the problem is that the const operator does not guarantee const-ness but rather merely asserts that the value pointed to by SOME_ARRAY_SIZE will not change at runtime. But why can the compiler not assume that the value is constant at compile time? It says 6 right there in the source code...

I think I'm missing something core in my fundamental understanding of C. Somebody help me out here. :)

[UPDATE]After reading a bit more around C99 and variable length arrays I think I understand this a bit better. What I was trying to create was a variable length array - const does not create a compile time constant but rather a runtime constant. Therfore I was initialising a variable length array, which is only valid in C99 at a function/block scope. A variable length array at the file scope is impossible as the compiler cannot assign a fixed memory address to an unbounded array.[/UPDATE]

like image 473
mmccomb Avatar asked Mar 31 '11 09:03

mmccomb


1 Answers

Well, in C++ the semantics are a bit different. In C++ your code would work fine. You must distinguish between 2 things, const and constant expression. Const means simply, as you described, that the value is read-only. constant expression, on the other hand, means the value is known compile time and is a compile-time constant. The semantics of const in C are always of the first type. The only constant expressions in C are literals, that's why #define is used for such kind of things.

In C++ however, any const object initialized with a constant expression is in itself a constant expression.

I don't know exactly WHY this is so in C, it's just the way it is

like image 190
Armen Tsirunyan Avatar answered Nov 02 '22 12:11

Armen Tsirunyan