Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why can't a const variable be used as an array size initializer? [duplicate]

Tags:

c

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

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;
}
like image 622
Mahmoud Tmam Avatar asked May 30 '17 16:05

Mahmoud Tmam


People also ask

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

Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.

What is the size of const variable?

An int type has a range of (at least) -32768 to 32767 but constants have to start with a digit so integer constants only have a range of 0-32767 on a 16-bit platform.

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

Declaring ArraysArray variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array. Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.

Do const variables need to be initialized?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .


Video Answer


1 Answers

In C, a const-qualified variable is not a constant expression1. A constant expression is something that can be evaluated at compile time - a numeric literal like 10 or 3.14159, a string literal like "Hello", a sizeof expression, or some expression made up of the same like 10 + sizeof "Hello".

For array declarations at file scope (outside the body of any function) or as members of struct or union types, the array dimension must be a constant expression.

For auto arrays (arrays declared within the body of a function that are not static), you can use a variable or expression whose value isn't known until runtime, but only in C99 or later.


  1. C++ is different in this regard - in that language, a const-qualified variable does count as a constant expression.

like image 175
John Bode Avatar answered Oct 22 '22 17:10

John Bode