0

I'm using Atmel 6.2 and writing an application for Arduino. I have a problem with these lines of code:

int total = 3;
uint64_t myarray[total] = {};

It gives the following error

error: array bound is not an integer constant before ']' token

Why is this happening?

Vinay Shukla
  • 1,818
  • 13
  • 41
Kaya311
  • 545
  • 2
  • 9
  • 21

4 Answers4

4

This

int total = 3;
uint64_t myarray[total] = {};

is a definition of a variable size array becaue the size of the array is not a compile-time constant expression.

Such kind of arrays is conditionally supported by C99. However this feature is not present in C++ (though some compilers can have their own language extensions that include this feature in C++) and the compiler correctly issues an error.

Either you should use a constant in the definition of the array for example like this

const int total = 3;
uint64_t myarray[total] = {};

or you should consider of using another container as for example std::vector<uint64_t> if you suppose that the ize of the array can be changed during run-time.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
3

You have to provide compile-time constants (or constexprs) as array size.

Use this:

const int total = 3;
anderas
  • 5,744
  • 30
  • 49
Nishant
  • 1,635
  • 1
  • 11
  • 24
1

"total" needs to be const. Also I would prefer std::array to C-style arrays (just personal preference).

int const total = 3;

std::array<uint64_t, total> values = {};

If you need a dynamic array, use std::vector.

Robinson
  • 9,666
  • 16
  • 71
  • 115
0

Your question is not very clear, you want to zero initialize or you want a fix to your Error.

As suggested you can make use of compile-time constant expression to fix error.

const int total = 3;
uint64_t myarray[total] = {};

To zero initialize you can use the following code.

std::fill_n(myarray, total, 0);

But, If you want a variable size array you can do it using pointers in the following manner.

int total = 3;

uint64_t  *myarray = new uint64_t [total]; // This will be created at run time
Vinay Shukla
  • 1,818
  • 13
  • 41