13

Why don't I get an error trying to create a negative-size array?

#include <array>

int main()
{
    std::array<int, -1> arr;
}

With -D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC I get no error. Is this intended behavior?

Jeffrey Bosboom
  • 13,313
  • 16
  • 79
  • 92
user6348851
  • 139
  • 1
  • 3

2 Answers2

20

No it's not legal. There's nothing about the specification of std::array that explicitly prevents this, but it's illegal because of narrowing conversions.

§14.3.2/5:

For a non-type template-parameter of integral or enumeration type, conversions permitted in a converted constant expression (5.19) are applied.

§5.19/3:

A converted constant expression of type T is a literal constant expression, implicitly converted to type T, where the implicit conversion (if any) is permitted in a literal constant expression and the implicit conversion sequence contains only user-defined conversions, lvalue-to-rvalue conversions (4.1), integral promotions (4.5), and integral conversions (4.7) other than narrowing conversions (8.5.4)

The only way to get GCC to complain is to enable -Wsign-conversion. This is a known bug and they haven't made any movement to fix it.

In Clang you get the expected error message:

error: non-type template argument evaluates to -1, which cannot be 
narrowed to type 'std::size_t' (aka 'unsigned long') [-Wc++11-narrowing]
    std::array<int, -1> arr;
  • 1
    Historical note: in published C++11 it was implementation-defined whether this was a narrowing conversion, but this was fixed by DR 1449 to always be narrowing – M.M May 18 '16 at 04:53
8

Type of std::array is:

template< 
    class T, 
    std::size_t N 
> struct array;

When you initialize second template parameter with -1, it is implicitly converted to a very large value as std::size_t is unsigned (which is illegal in C++ as pointed by other answer and it should be diagnosed).

Another possibility is that your arr is optimized out. You can confirm this by adding -fdump-tree-optimized flag to gcc command line.

If you ensure arr is not optimized out, I hope you should get the following warning:

prog.cpp:5:25: error: size of variable 'arr' is too large
     std::array<int, -1> arr;
Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • 1
    Doesn't optimization happen after such warning checks? – BartoszKP May 18 '16 at 08:02
  • 1
    @BartoszKP I used `gcc --std=c++11 -O2 -fdump-tree-optimized arr_que.cpp` and confirmed that code is optimized to just `return 0;` as you might expect. I am not sure whether template parameter misuse must be diagnosed. – Mohit Jain May 18 '16 at 08:46