0

I'm currently plodding along through C++ Primer by Stanley Lippman, and in an example for constexpr functions learned that a function like

constexpr size_t geom(size_t cnt) { return new_sz() * cnt * 10;}

is not required to return a constant expression, and only does so if it's argument is a constant expression. Hence, if I try to use the return of geom with a non-constant argument in a context which requires a constant expression like as the dimension in an array initialization, the compiler should produce an error indicating geom is not a constant expression.

So I would think, as per the book's example with nearly identical code, that arr would be okay in the following example, and a2 would produce a compile-time error

#include<iostream>
#include<string>
#include<vector>
#include<cctype>
using std::cin; using std::cout; using std::endl; using std::string;
using std::vector; using std::end; using std::begin; using std::getline;
using std::initializer_list;

constexpr int new_sz() { return 42;}
constexpr size_t geom(size_t cnt) { return new_sz() * cnt * 10;}

int main()
{
    int arr[geom(2)];
    int i = 10;
    int a2[geom(i)];
    return 0;
}

But this compiles fine. In fact, I can even make geom and new_sz() non-constexpr functions and it still compiles fine. I though maybe geom was somehow implicitly being made into a constexpr function so I went as far as to write this clearly non-constexpr function test

int test(int a, int b){ 
    if (a > b) return a;
    else return b;
}

and use it in an array initialization, and it works as well. What is going on? Is this compiler-specific? I am using GCC 4.9.2 32-bit release. I took a look at the cpp reference for array declarations to see if I was maybe lost on what the dimension could be, but it is supposed to be an integral constant expression... I can't figure out what I'm missing here.

Eric Hansen
  • 1,749
  • 2
  • 19
  • 39

0 Answers0