Why should global array size be an integer constant? - c++

In C++ I tried declaring a global array of some size. I got the error:
array bound is not an integer constant before ‘]’ token
But when I declared an array of the same type in the main() function it is working fine.
Why is there different behaviour here?
int y=5;
int arr[y]; //When I comment this line it works fine
int main()
{
int x=5;
int arr2[x]; // This line doesn't show any error.
}
Edit: Many are suggesting this question is a duplicate of Getting error "array bound is not an integer constant before ']' token". But that question doesn't answer why there is different behaviour.

Both examples are ill-formed in C++. If a compiler does not diagnose the latter, then it does not conform to the standard.
Why there is a different behaviour here?
You use a language extension that allows runtime length automatic arrays. But does not allow runtime length static arrays. Global arrays have static storage.
In case you are using GCC, you can ask it to conform to the standard by using the -pedantic command line option. It is a good idea to do so in order to be informed about portability problems.

The size of an array must be a constant. You can fix this by declaring y as const.
const int y=5;
int arr[y];
As for why this worked in main, g++ does allow a variable length array in block scope as an extension. It is not standard C++ however.

Both shouldn't be used, one works because (as #eerorika said) automatic length arrays are allowed on runtime, but global arrays need to have static storage.
If you want to declare an array with a variable size (e.g. given by std::cin) you would do something along the lines of:
int x;
std::cin >> x;
const int n = x;
float arr[n];
But you wouldn't be able to set it to contain just zeros with float arr[n] = {0} (if you need to add to a value in the array, not being sure you set it), you would need to use a loop like that
for(int i = 0; i < n; i++)
{
arr[i] = 0;
}

The type-system of C++ handles these C-like arrays in a way that it defines arr2 from your example of type int[5]. So, yes the number of elements of the array is part of the type!
This puts some constraints on what you are allowed to use in the definition of C-like arrays. I.e. this number needs to have static storage, needs to be immutable and needs to be available at compile time.
So, you might want to change your code to something like the following, which will have another goodie. It initializes the array in a proper way:
int arr2[] = {0, 0, 0, 0, 0};

Related

Using Arrays as Global Variables

I am trying to use arrays as global variables. It seems that I cannot use a previously initialized variable such as l for dimensioning the arrays and I get the following error
error: array bound is not an integer constant before ']' token.
However, this is possible when I try to use the same thing inside the main function.
Can someone explain what is happening here?
// If you move the following lines inside the main function then everything works fine
int l = 3;
int a[l] = {1, 2, 3};
int main()
{
return 0;
}
Arrays with global scope or defined as static need dimensions known at compile time, and as Neil says, declaring l as const achieves this.
As a gcc / clang extension, arrays allocated within a function (i.e. allocated on the stack) can have dimensions known only at runtime. This is not standard however, and (for example) MSVC does not permit it.
Just change l to
const int l=3;

C++ examples where dynamic array is required instead of static array

I am trying to understand the difference between static and dynamic arrays in C++ and I can not think of a case where a static array would not do the trick.
I am considering a static array that would be declared this way:
int N=10;
int arr[N];`
I read here that the main difference between static and dynamic array is that a static array is allocated during compilation so N needs to be know at compilation.
However, this explains that arrays declared this way can also be Variable-length arrays:
Variable-length arrays were added in C99 - they behave mostly like fixed-length arrays, except that their size is established at run time; N does not have to be a compile-time constant expression:`
and indeed, the following c++ code is working, even though n is only known at runtime :
int n =-1;
std::cin>>n;
int arr[n];
//Let the user fill the array
for(int i=0; i<n;i++){
std::cin>>arr[i];
}
//Display array
for(int i=0; i<n;i++){
std::cout<<i<<" "<<arr[i]<<std::endl;
}
So I would like an example of code were a static arrays defined like this would not work and the use of dynamic array would be required ?
The code doesn't work on all compilers because variable length arrays aren't part of C++. They are part of C as of ISO C99, and some compilers will allow VLAs in C++, but it's not a portable solution. GCC, for instance, allows VLAs, but warns the user (-Wno-vla).
Below the hood, VLAs are dynamic anyway as the compiler can't reserve the appropriate amount of stack memory because it doesn't know how big the array is going to be. Instead of VLAs, std::vector can be used for dynamic memory that gets deallocated at the end of the scope.

reference to an array of size determined at run-time

I tried to find this but can't find any. I know I can create a reference to an array variable:
int x[10] = {}; int (&y)[10] = x;
However, in the case that the array size is not known at compile time, like in the following code:
const int n = atoi( string ); //the string is read from a text file at run time.
int x[n] = {}; int (&y)[n] = x; //this generates a compiling error.
Even if int n is declared const, as long as n is not known at compile time, the reference is invalid. The compiler will say something like this: reference to type 'int [n]' cannot bind to a value of unrelated type 'int [n]'. Anyone has any idea about how to fix this? Thanks in advance.
Runtime-length arrays are a C99 feature and do not exist in standard C++. They're present as an extension on some C++ compilers, but don't mix well with C++ features, like references and templates.
You should probably use a vector.
The feature of declaring arrays dynamically like shouldn't be used in C++. Not all compilers support it. Consider using the STL containers instead. Like std::vector<int>

Array Size Declaration issue [duplicate]

This question already has answers here:
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 8 years ago.
int n=5;
int arr[n];
I want to declare size of array as above in C++, but I get error while compiling. I find a lot of code in internet which uses these type of declaration instead of simple putting int arr[5]. How come the code compiles successfully for them but not for me. P.S: I use windows7 and Visual Studio(IDE).
Error Message : Expresion must have a constant value
The number of elements of the array, the array bound, must be a constant expression.
You have to use
const int n = 5;
or
constexpr int n = 5;
else it is a non standard extension : variable length array (VLA).
The error message actually describes rather well what’s going on: C++ does not support arrays with a non-constant size (more precisely, the size needs to be known at compile time).
There are two solutions for this:
If the size is actually a constant, declare it as constexpr (if you can’t use C++11, you can also use const):
constexpr int n = 5;
std::array<int, n> arr;
Which requires the standard header <array>. Or, if you cannot use C++11, change the second line to
int arr[n];
If the size isn’t known at compile time, don’t use a static array, use a dynamic container instead:
int n = 5;
std::vector<int> arr(n);
This requires the <vector> standard header.

Defining Array C/C++

What is the difference between this two array definitions and which one is more correct and why?
#include <stdio.h>
#define SIZE 20
int main() {
// definition method 1:
int a[SIZE];
// end definition method 1.
// defintion method 2:
int n;
scanf("%d", &n);
int b[n];
// end definition method 2.
return 0;
}
I know if we read size, variable n, from stdin, it's more correct to define our (block of memory we'll be using) array as a pointer and use stdlib.h and array = malloc(n * sizeof(int)), rather than decalring it as int array[n], but again why?
It's not "more correct" or "less correct". It either is xor isn't correct. In particular, this works in C, but not in C++.
You are declaring dynamic arrays. Better way to declare Dynamic arrays as
int *arr; // int * type is just for simplicity
arr = malloc(n*sizeof(int*));
this is because variable length arrays are only allowed in C99 and you can't use this in c89/90.
In (pre-C99) C and C++, all types are statically sized. This means that arrays must be declared with a size that is both constant and known to the compiler.
Now, many C++ compilers offer dynamically sized arrays as a nonstandard extension, and C99 explicitly permits them. So int b[n] will most likely work if you try it. But in some cases, it will not, and the compiler is not wrong in those cases.
If you know SIZE at compile-time:
int ar[SIZE];
If you don't:
std::vector<int> ar;
I don't want to see malloc anywhere in your C++ code. However, you are fundamentally correct and for C that's just what you'd do:
int* ptr = malloc(sizeof(int) * SIZE);
/* ... */
free(ptr);
Variable-length arrays are a GCC extension that allow you to do:
int ar[n];
but I've had issues where VLAs were disabled but GCC didn't successfully detect that I was trying to use them. Chaos ensues. Just avoid it.
Q1 : First definition is the static array declaration. Perfectly correct.
It is when you have the size known, so no comparison with VLA or malloc().
Q2 : Which is better when taking size as an input from the user : VLA or malloc .
VLA : They are limited by the environment's bounds on the size of automatic
allocation. And automatic variables are usually allocated on the stack which is relatively
small.The limitation is platform specific.Also, this is in c99 and above only.Some ease of use while declaring multidimensional arrays is obtained by VLA.
Malloc : Allocates from the heap.So, for large size is definitely better.For, multidimensional arrays pointers are involved so a bit complex implementataion.
Check http://bytes.com/topic/c/answers/578354-vla-feature-c99-vs-malloc
I think that metod1 could be little bit faster, but both of them are correct in C.
In C++ first will work, but if you want to use a second you should use:
int size = 5;
int * array = new int[size];
and remember to delete it:
delete [] array;
I think it gives you more option to use while coding.
If you use malloc or other dynamic allocation to get a pointer. You will use like p+n..., but if you use array, you could use array[n]. Also, while define pointer, you need to free it; but array does not need to free.
And in C++, we could define user-defined class to do such things, and in STL, there is std::vector which do the array-things, and much more.
Both are correct. the declaration you use depends on your code.
The first declaration i.e. int a[size]; creates an array with a fixed size of 20 elements.
It is helpful when you know the exact size of the array that will be used in the code. for example, you are generating
table of a number n up till its 20th multiple.
The second declaration allows you to make an array of the size that you desire.
It is helpful when you will need an array of different sizes, each time the code is executed for example, you want to generate the fibonacci series till n. In that case, the size of the array must be n for each value of n. So say you have n = 5, in this case int a [20] will waste memory because only the first five slots will be used for the fibonacci series and the rest will be empty. Similarly if n = 25 then your array int a[20] will become too small.
The difference if you define array using malloc is that, you can pass the size of array dynamically i.e at run time. You input a value your program has during run time.
One more difference is that arrays created using malloc are allocated space on heap. So they are preserved across function calls unlike static arrays.
example-
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
int *a;
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
return 0;
}