Search code examples
c++uint64atmelstudio

How to initialize a uint64_t array to 0 in C++?


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?


Solution

  • 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.