Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can define the length of an array using a constant, so why doesn't int d[b] work?

Tags:

c++

int a = 5;
const int b = a, c = 4;

int e[a];
int d[b];
int f[c];

The definition of f[c] is valid.
The variable b is also a constant int, but the compiler gave me the error "expression must have a constant value" for the line int d[b]. What are the differences between b and c?

like image 210
OliverShang Avatar asked Nov 14 '19 14:11

OliverShang


People also ask

How do you define the length of an array?

Description. The length property of an array is always one larger than the index of the highest element defined in the array. For traditional “dense” arrays that have contiguous elements and begin with element 0, the length property specifies the number of elements in the array.

Can an array be a constant?

Arrays are Not Constants It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

Do you have to define the length of an array in Java?

Answer: No. It is not possible to declare an array without specifying the size. If at all you want to do that, then you can use ArrayList which is dynamic in nature. Q #2) Is Array size fixed in Java?

Can array length be a variable?

In computer programming, a variable-length array (VLA), also called variable-sized or runtime-sized, is an array data structure whose length is determined at run time (instead of at compile time). In C, the VLA is said to have a variably modified type that depends on a value (see Dependent type).


2 Answers

what are the differences between b and c?

c has a compile time constant initialiser, while b does not. A const object with compile time constant initialiser is itself a compile time constant value.

Since I can define an lenth of an arry using a constant ,so why don't this work?

Not just any constant will do. const qualifier implies runtime constness (i.e the value may be determined at runtime but won't change throughout the lifetime of the object). Only compile time constant values can be used as array size.

like image 68
eerorika Avatar answered Oct 13 '22 15:10

eerorika


You are using a non-constant variable to assign value to a constant. Therefore, that variable's value can't be determined compile time. I know you aren't changing a, but the compiler does not think like this.

like image 43
CoderCharmander Avatar answered Oct 13 '22 16:10

CoderCharmander