Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a two dimensional array with class static const integers

I'm declaring a three-dimensional array as a class member, using static const class members as the first two bounds:

class A
{
    static const uint8_t screenWidth = 256;
    static const uint8_t screenHeight = 240;

    uint8_t buffer[screenHeight][screenWidth ][3];
}

in Visual Studio 2019 I get the following (weird?) error:

Error (active)  E0098   an array may not have elements of this type

if I resort to the "enum hack" in order to declare class-local compile time integer constants it works:

class A
{
    enum { SH = 240, SW = 256};
    uint8_t buffer[SH][SW][3];
}

shouldn't the former example be C++11 compliant code? (I guess Visual Studio 2019 compiler is).

like image 579
Luca Avatar asked Sep 04 '26 22:09

Luca


2 Answers

I think that an object of the type uint8_t is unable to contain the value 256.:)

Why not just to use the type size_t instead of the type uint8_t?

static const size_t screenWidth = 256;
static const size_t screenHeight = 240;
like image 186
Vlad from Moscow Avatar answered Sep 07 '26 13:09

Vlad from Moscow


The problem you have is that, in the declaration:

static const uint8_t screenWidth = 256;

the value 256 is not valid for a uint8_t type (range is 0 thru 255), and it 'rolls over' to give an actual value of zero - which is invalid for an array dimension.

Make your dimension 'constants' bigger types, and your code will work:

class A {
    static const uint16_t screenWidth = 256;
    static const uint16_t screenHeight = 240;

    uint8_t buffer[screenHeight][screenWidth][3];
};
like image 24
Adrian Mole Avatar answered Sep 07 '26 13:09

Adrian Mole