Open In App

Why can’t a const variable be used to define an Array’s initial size in C?

What is an array?

An array is a collection of items of the same data type stored at contiguous memory locations.

This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index 0 and the difference between the two indexes is the offset.



Const Variables:

There are a certain set of rules for the declaration and initialization of the constant variables:



Why can’t constant values be used to define an array’s initial size?

In simple words, it is the drawback of the C programming language. The sizes of statically-bounded arrays need to be constant expressions, whereas in C that’s only something like a literal constant or a sizeof() expression, but not a const-typed variable. The reasons are listed below:

In the following code, const int cannot be used as an array size:




#include <stdio.h>
  
const int sz = 0;
typedef struct
{
    char s[sz];
} st;
  
int main()
{
    st obj;
    strcpy(obj.s, "hello world");
    printf("%s", obj.s);
    return 0;
}

Output:

timeout: failed to run command ‘./b2204e76-8907-4eb8-a8d6-ce153abe1dc1’: No such file or directory

This is another deficiency in the C language, which is fixed later in C++. In that language, a const-qualified variable does count as a constant expression.

In this case, if we are using const inside the main() function then const value can be used to initialize array size and the program runs without any compile-time or run-time error.




#include <bits/stdc++.h>
using namespace std;
  
// Driver Code
int main()
{
    const int n = 5;
    int arr[n], i;
  
    for (i = 0; i < n; ++i)
        arr[i] = i;
  
    for (i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Output
0 1 2 3 4 

Note: A constant variable can be used to initialize the array size but before declaring an array, the const variable must be assigned some value. But the data items can be accessible if we are using const variable. 


Article Tags :