tags:

views:

395

answers:

2

Can someone please explain (what might be my perceived) disparity in errors in the following code? Essentially why are "//OK" okay and "//error" errors?

(Compiler is i686-apple-darwin9-g++-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5490))

#include <cmath>
#include <iosfwd>

template <typename T>
class TT{
   char _c[sizeof(T) + static_cast<size_t>(::ceil(sizeof(T) * 0.001)) + 1];    // error: array bound is not an integer constant
   //char _c[sizeof(T) + static_cast<size_t>(sizeof(T) * 0.001) + 1];  // OK
   T _t;
};

class IS{
   unsigned char* _u;
   double _d;
};

char s[static_cast<size_t>(::ceil(sizeof(TT<IS>) * 10.0))]; // error: array bound is not an integer constant

int main(int argc, char** argv){
  char a[static_cast<size_t>(10.0)];  // OK
  char b[static_cast<size_t>(::ceil(sizeof(double) * 10.0))]; // OK

  TT<int> it;
  char c[static_cast<size_t>(::ceil(sizeof(TT<int>) * 10.0))];    // OK

  TT<IS> is;
  char d[static_cast<size_t>(::ceil(sizeof(TT<IS>) * 10.0))]; // OK

  return 0;
}

As a side note, I am aware of C++0x: Generalized constant expression.

A: 

Prototype of ceil function

double ceil (      double x );
float ceil (       float x );
long double ceil ( long double x ); <cmath>

Round up value - It returns the smallest integral value that is not less than x.

http://www.cplusplus.com/reference/clibrary/cmath/ceil/

adatapost
+4  A: 

The problem is in where the arrays are declared.

You can's declare an array with non-constant size at file level since the compiler needs to know at compile time how much to allocate and in your case this would require a function call.

When you do the same at function level the C++ extension your compiler supports kicks in (this is not allowed by the standart) – the compiler emits code that will call the function, compute the value and allocate the array on stack in runtime.

sharptooth
That's what I wanted to verify. In a function having ceil() (or any other function for that matter) in array declaration doesn't break any language semantics/rules. But, in a class having an array's size depend on a function would break sizeof(). In this case sizeof(TT) is not available at compile time.Thanks a lot! Appreciate your time!
kvs
Great answer sharptooth. BTW, with Microsoft's Visual C++ compiler, you can't do this at function level as well.
Aamir