0
constexpr int f(int idx) { constexpr auto arr = std::array<int, 1'000'000'000>{}; // stack overflow? return arr[idx]; } int main() { return f(1024); } 
  • Does arr occupy the stack space?
  • Is the compiler permitted to make arr not occupy the stack space?
  • Is it mandated for the compiler to avoid arr occupies the stack space?
7
  • 1
    unless used in a constexpr context, you can never assume a constexpr function will run at compile time. Commented Jul 7 at 4:49
  • 1
    @NathanOliver GCC will do this optimisation: godbolt.org/z/WYohe7cP8 Commented Jul 7 at 5:02
  • 1
    so it looks like it will do almost anything. even just fail to compile with MSVC. Commented Jul 7 at 5:04
  • 1
    The short answer is yes, it does occupy stack space (though some compilers optimize that into static memory). Another way to phrase the question is "Does it make any difference if I put static on it, or does it already have static storage duration?". See the linked duplicates. Commented Jul 7 at 5:43
  • 1
    Your f() can be evaluated at compile time to return 0. So your compiler will most likely do so. Or if it cannot instantiate that array at compile time it will fail compilation. Commented Jul 7 at 8:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.