Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static const + const as array bound

Tags:

c++

arrays

qnx

I'm doing something like this

Class.hpp:

 class Class {

 private:
     static const unsigned int arraySize;
     int ar[arraySize+2];
 };

Class.cpp:

#include <Class.hpp>
const unsigned int arraySize = 384;

The compiler (q++, a c++ compiler for the QNX OS based on g++) gives me error: array bound is not an integer constant while compiling a unit including Class.hpp (not while compiling Class.cpp).

Why isn't that working? I know that a static const member can be used as an array bound, guaranteed by the C++ standard (see this anwser). But why doesn't the compiler see the result of static const + const as a constant?

like image 964
MBober Avatar asked Jan 20 '12 08:01

MBober


2 Answers

This is good code which should have been accepted by the compiler:

class Class { 
  const static int arraySize = 384; 
  int ar[arraySize+2]; 
}; 

and if it isn't, your compiler is broken.

However, if you move actual constant out of the header file to selected translation unit, that invalidates the code.

// Class.h
class Class { 
  const static int arraySize;
  int ar[arraySize+2]; // ERROR
}; 

// Class.cpp
const int Class::arraySize = 384;

This is because the size of your Class object cannot be determined at compile time from the data available in the header alone. This is not exactly right reason, but reasoning along these lines helps to understand compilation errors such as this.

To avoid making such mistakes, you can replace static const int with an enum, e.g.

class Class { 
  enum { arraySize = 384 }; 
  int ar[arraySize+2]; 
}; 
like image 74
bronekk Avatar answered Oct 10 '22 16:10

bronekk


I'm surprised this actually compiles on gcc, as a comment says. Since the 384 isn't in the header file, the size of the Class is not known to other compilation units. It might not matter in some compilation units depending on how/if they are using Class, but I can't imagine this compiling:

// this is a source file called, say, blah.cpp
#include <Class.hpp>

void someFunc()
{
    void *mem = malloc(sizeof(Class));  // size is not known, so this can't compile

    // do something with mem
}

You need to have in your .hpp:

class Class {

 private:
     static const unsigned int arraySize = 384;
     int ar[arraySize+2];
 };

.. as it is in the OP that you link to here.

like image 36
Jim Buck Avatar answered Oct 10 '22 17:10

Jim Buck