Can a const variable be used to declare the size of an array in C?

const int array size c++
declare array without size in c
can the size of an array be declared at runtime in c++
c variable length array
input array of unknown size c
c variable length array in struct
c++ variable length array
variable length array declaration not allowed at file scope

Why does the following code throw an error?

const int a = 5;
int b[a]={1,2,3,4,5};

And also when I tried to compile the above code without "const" keyword, I got the same error:

int a = 5; 
int b[a]={1,2,3,4,5};

why is it so? What is the mistake that I am doing here?

And also another question: When are constants replaced with their actual values in a code, i.e if I declare a variable say: const int x= 5; I know that no memory is allocated in RAM for the variable x, but constant variable area in ROM holds the value 5 and that x is simply replaced by the value 5 everywhere x appears in the code. But when does this happen? Compilation time? Boot up time? Preprocessing time?

PS: I am talking about Embedded C (running on a Microcontroller etc), not C running on my desktop. So the embedded system is bound to have a ROM (Flash, EEPROM...). What would happen then?

It's simply a limitation of the language. The sizes of statically-bounded arrays need to be constant expressions, and unfortunately in C that's only something like a literal constant or a sizeof expression or such like, but not a const-typed variable.

(As Simon pointed out, since C99 there are also runtime-bounded arrays, or "variable-length arrays", whose size can be given by the value of any variable. But that's a different animal.)

You may be interested to hear that the rules are different in C++, where a static const int is indeed a constant expression, and C++11 even adds a new keyword, constexpr, to allow even more general use of constant expressions which encompass more things whose value "could reasonably be determined at compile time".

In C, why can't a const variable be used as an array size initializer , Background: The final abitator of what you can and cannot do in C is determined by the compiler(s) you are using. Most programmers I know,  Can a const variable be used to declare the size of an array in C? (4) 2 major alternatives to VLA: enum and macros. With enum: enum N { N = 5 }; int is[N]; This works because enum members are constant expressions: Can enum member be the size of an array in ANSI-C? With macros:

In C, const is a misnomer for read-only. const variables can change their value, e.g. it is perfectly okay to declare

const volatile int timer_tick_register; /* A CPU register. */

which you can read and get a different value with each read, but not write to. The language specification thus treats const qualified objects not as constant expressions suitable for array sizes.

Array declaration - cppreference.com, Your question has 2 parts actually. 1/ How can I declare the constant size of an array outside the array? You can either use a macro #define ARRAY_SIZE 10  Can't use a variable for my array size but variable is declared as a const Int. edit: I should mention that the objective of the project is to only use array objects. I think the rule is kind of dumb anyways but thank you guys for all the help so far.

How can I declare an array of variable size (Globally), An array subscript can be a literal value, a variable (constant or non-constant), When declaring a fixed array, the length of the array (between the square Note that non-const variables or runtime constants cannot be used:  int a = 2; const int size = a; int array[size] = {0}; However, a is a variable, which means that the value a could be changed, and will be sure at run-time So the compiler forbids you. You can use. int a = 2; int size = a; int* array = new int[size]; thus, you can apply for an array with dynamic size.

EDIT: Just read on wikipedia that C11 has relegated variable length arrays to an optional feature :( Doh! The first half of the post may not be that useful but the second half answers some of your other questions :)

As an extra to Kerrek SB's post, C99 (ISO/IEC 9899:1999) does have the concept of a variable length array. The standard gives the following example:

#include <stddef.h>
size_t fsize3(int n)
{
    char b[n+3]; // variable length array
    return sizeof b; // execution time sizeof
}

The sizeof operator is extended as follows:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

Another nice example can be found on wikipedia.

Note that statically declared cannot be variable length arrays.

As for some of your other questions:

Q: When are constants replaced with their actual values in a code?

If the constant is a const variable then it may never be "replaced" and could always be accessed as an area of memory. This is because the address-of operator & still has to work with the variable. However, if the variable address is never used then it can be "replaced" and have no memory allocated. From the C standard:

The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.

Next question...

Q: I know that no memory is allocated in RAM for the variable x, but constant variable area in ROM holds the value 5

This depends on your system. If you have ROM and the compiler knows where ROM is located then it may well be placed in ROM. If there is no ROM the only choice the compiler (well linker really) will have is RAM.

Q: x is simply replaced by the value 5 everywhere x appears in the code. But when does this happen? Compilation time? Boot up time? Preprocessing time?

As noted, this rather depends on how the constant is used. If the address of the const variable is never used and the compiler is clever enough, then at complilation time. Otherwise the "replacement" never occurs and it is a value with a location in memory; in this case the placement of the variable in memory happens at link time. It will never occur during preprocessing.

6.1, Using constexpr keyword: Using constexpr in C++(not in C) can be used to Hence in order to make it as constant, we have to declare the variable 'var' with const keyword. Declare a C/C++ function returning pointer to array of integer pointers Variable Length Arrays in C and C++ · How to modify a const variable in C? a has variable length array type, because size is not an integer constant expression. Thus, it cannot have an initializer list. In C90, there are no VLAs, so the code is illegal for that reason. In C++ there are also no VLAs, but you could make size a const int. That's because in C++ you can use const int variables in ICEs. In C you can't.

Maybe it is worth to mention, here you could use

int b[] = {1, 4, 5};

In case you will need number of elements

 size_t sz = sizeof(b)/sizeof(b[0]);

I believe it is up to tool chain, to decide where to store constants, flash or RAM

Different ways to declare variable as constant in C and C++ , Using #define preprocessor directive: This directive is used to declare an alias name for existing variable or any value. We can use this to declare a constant as​  The #define directive is a preprocessor command. It’s followed by the name of the symbol being defined, VOTING_AGE. These symbols are named like variables, though using ALL CAPS for constants lets you easily identify constants versus variables in your source code. The symbol must be all one word.

Constants in C/C++, As a result, the expression array [pos] = value can be used by an attacker to Arrays containing a constant number of elements can be declared as follows: The C Standard adds support for variable length arrays or arrays whose size is  The sizes of statically-bounded arrays need to be constant expressions, and unfortunately in C that's only something like a literal constant or a sizeof expression or such like, but not a const-typed variable.

ARR00-C. Understand how arrays work, Dimensions used when declaring arrays in C must be positive integral constants In C99, dimensions must still be positive integers, but variables can be used, const int NROWS = 100; // ( Old code would use #define NROWS 100 ) const int  That's an implementation detail. I believe GCC places it on the stack, like normal automatic variables. It may or may not use dynamic allocation if the size is too large for the stack; I don't know myself. According to this the compiler allows this expression in C++ as far as C90/99.

C Programming Course Notes, Const Qualifier in C The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (Which depends upon where const variables are stored, we may change the value of const variable by using pointer). The result is implementation-defined if an attempt is made to change a const.

Comments
  • Compilation time. btw ROM is like dvd's and such, there is no built in ROM in a PC (when would it be populated anyway?)
  • @Vprimachenko: OT: Couldn't the BIOS be considered ROM? At least there where days you had to pull it out of its socket to re-write it.
  • You could use an enum instead of a const.
  • @alk you're right, didn't thought of that
  • The rules are different in C99 as well, though the array will be considered to be dynamic.
  • @SimonElliott: What are the rules for C99? Or more importantly, for C11? (Or were you just referring to VLAs?)
  • :I was just on about VLAs
  • "But you should avoid using variable length arrays because they may incur an overhead." - what overhead?
  • @MattMcNabb updated with link to stackoverflow.com/questions/2034712/… in which top answers say there may be overhead
  • This answer is the only one with a solution (enum instead of #define - yuck).
  • @ctn yes, the endless joys of C. But I'm "confident" constexpr will make it in C2x :-)
  • Thanx for your answer! Your answers are great! But its my mistake. I forgot to mention, I am talking about Embedded C, code running on an embedded system. So it is bound to have a ROM (Flash, EEPROM) etc. What would happen in that case?
  • If you take the address of the const variable at any point the compiler/linker will have to create a memory location for the variable. At compile time the symbol is created. At link time the linker will figure out where to store the variable. This will be determined by some kind of linker directive file. If the const variable never has it's address taken then, assuming the compiler is smart enough, it could optimize it out and not allocate any storage for it, it which case the "replacement" so to speak happens during compile time