3

The C program below fails to compile with gcc due to an error about the size of test_array not being a compile time constant. Why?

struct HWND__ { int unused; }; 
typedef struct HWND__ *HWND;

void test()
{
   static int test_array[ (unsigned long long)((HWND)1) ];
}

Error produced is:

test.c: In function ‘test’:
test.c:5:14: error: storage size of ‘test_array’ isn’t constant
   static int test_array[ (unsigned long long)((HWND)1)  ];
              ^
Andrew Rice
  • 123
  • 7
  • 1
    Possible duplicate: http://stackoverflow.com/questions/3025050/ – Mio Bambino Aug 04 '16 at 09:36
  • 3
    Why don't `static int test_array[ 1 ]` or simply `static int test_array`? Smell like XY problem. What you're trying to achieve? – LPs Aug 04 '16 at 09:40
  • 1
    There are no "casts to struct" in C – M.M Aug 04 '16 at 09:41
  • 4
    @M.M That's a cast to "pointer to struct", which is fine (just not here) – ams Aug 04 '16 at 09:42
  • I'm in the middle of building a cross compiling GHC compiler which will produce windows binaries from linux. The example I have here is distilled from C code autogenerated from a Haskell source file using hsc2hs as part of the compilation process. – Andrew Rice Aug 04 '16 at 09:43
  • I wonder why the error message doesn't point `^` to the size... – Karoly Horvath Aug 04 '16 at 09:47
  • 1
    Clang 3.8 says "warning: variable length array folded to constant array as an extension", but only with `-pedantic`. – ams Aug 04 '16 at 09:50
  • Note that `typedef` and `struct` are not issue here: `static int test_array[ (unsigned long long)((int*)1) ];` seems to cause error as well. – user694733 Aug 04 '16 at 10:00
  • Maybe it's a compiler bug. Declaring `test_array` outside of function seems to work. – user694733 Aug 04 '16 at 10:04

1 Answers1

3

From the C11 standard, section 6.6:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.

An integer constant expression is required in a number of contexts such as the size of a bit-field member of a structure, the value of an enumeration constant, and the size of a non-variable length array.

I think that's why your code is invalid.

I suggest submitting a bug report to the hsc2hs developers, and fixing up these cases manually in the meantime.

ams
  • 24,923
  • 4
  • 54
  • 75