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;
}
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.
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.
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.
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 .
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.
const
-qualified variable does count as a constant expression.
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