2
class sarray
{
public:
    static const unsigned int iarr_size;

    void add(const char c ) {}

private :   
    unsigned char iarr[iarr_size];
    unsigned int off;

public 

};

Why do unsigned char iarr[iarr_size] give me a not constant expression error for iarr_size??

iarr_size is declared as const.

Sorry for my bad english.

1 Answer 1

3

You should initialize iarr_size with an unsigned int. For example:

class sarray
{
public:
    static const unsigned int iarr_size = 5;

    void add(const char c ) {}

private :   
    unsigned char iarr[iarr_size];
    unsigned int off;

public 

};

The better solution is that the member iarr will be a pointer to unsigned char, and in the constructor use new to allocate the array:

class sarray
{
public:
    sarray()
    {
        int i = 5; // any int
        iarr = new unsigned char[i];
    }
    void add(const char c) {}

private:
    unsigned char* iarr;
    unsigned int off;
};
3
  • that will cause multiple definition error if i separate compilation
    – KarimS
    Commented Dec 24, 2015 at 21:40
  • 1
    Don't seperate. const should be determined in cimpile time, so you should initalize it with a value. Just give it a value. The better solution is that the member iarr will be a pointer to unsigned char, and in the constructor use new to allocate the array. Commented Dec 24, 2015 at 21:41
  • ok thank you, i know dynamic allocation is better in this case, just learning c++ syntax(i'm moving from c to c++).
    – KarimS
    Commented Dec 24, 2015 at 21:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.