2

I found running the following code (clang 5.0/gcc7.1 with std=c++17) at compiling time, it will report an out of bounds error

int dummy[1];

struct CTest {
  constexpr CTest()  {
        dummy[100] = 1;
  }
};

constexpr CTest t;  // error: array subscript value ‘100’ is outside the bounds of array ‘dummy’ of type ‘int [1]’

But running a normal function in compiling time, it will not report the error.

constexpr int foo(int i)
{
    dummy[1000] = i;
    return i;
}
int a[foo(1)];    //force foo run at compile time, no compile error

I am wondering whether this behavior is well-defined that in in literal class constructor it will check the boundary.

camino
  • 10,085
  • 20
  • 64
  • 115
  • Related: https://stackoverflow.com/q/45487308/1896169 – Justin Oct 23 '18 at 21:30
  • GCC supports VLAs, so you should not expect an error when sizing an array at run-time - use `-pedantic` to get a warning. –  Oct 23 '18 at 21:30
  • 1
    @NeilButterworth are you sure you got the question correctly? – SergeyA Oct 23 '18 at 21:32
  • Out of bounds accesses and other UB *in constant expressions and constexpr functions* are diagnosable and required to be reported. UB elsewhere may or may not go unnoticed. [see e.g.](https://stackoverflow.com/questions/7421170/constexpr-undefined-behaviour) – n. m. could be an AI Oct 23 '18 at 21:38
  • @Justin That is different question, because here I define dummy[1], not dummy[0] – camino Oct 23 '18 at 21:40
  • @camino Yes. That's why that question is only "Related" – Justin Oct 23 '18 at 21:43

0 Answers0