0

The following code works well in clang++3.6/g++4.8.2, ubuntu. I am wondering why this code could compile(using -std=c++14/c++11) and also print out the correct result "4". To my understanding the value of *pi could only be calculated at running time and the length of array need to be calculated in compiling time, right?

constexpr int foo(int i,int j)
{   
    return i+j;
}   

int bar(int *p)
{
    int i=pow(2,*p);
    return i;
}  

int main()
{
    int *pi = new int;
    *pi = 1;
    *pi = bar(pi);
    int arr3[foo(*pi,*pi)]; // the length of array need to be calculated in compile time
    cout<<sizeof(arr3)/sizeof(arr3[0])<<endl;

}
camino
  • 10,085
  • 20
  • 64
  • 115
  • possible duplicate of [When should you use constexpr capability in C++11?](http://stackoverflow.com/questions/4748083/when-should-you-use-constexpr-capability-in-c11) – philipxy Feb 15 '15 at 21:35
  • A constexpr _can_ be evaluated at compile time. But the result of a constexpr is only a constexpr if the inputs are also constexpr's. – Cubic Feb 15 '15 at 21:37
  • 2
    Try compiling it with `-pedantic-errors` option. – Nawaz Feb 15 '15 at 21:40
  • At compile time, no concept of memory exists. `constexpr int i = 1; constexpr int size = foo(i, i); int arr[size];` works fine. Don't use pointers everywhere and prefer `std::array` to avoid VLAs in disguise. – stefan Feb 15 '15 at 21:44

1 Answers1

0

It is calculated at run time.

int arr3[expr]

doesn't need a known, at compile time, size value. So the thing is that without optimizations g++ saves array size in a local variable or with optimizations it performs some static analysis. And this is how it knows sizeof at runtime.

For example:

#include <stdio.h>

int main()
{
    int i;
    scanf("%d", &i);
    int arr3[i];
    printf("%d\n", sizeof(arr3));
}

generates the following assembly fragment (g++ -S -O3)

movl    -4(%rbp), %esi
shlq    $2, %rsi
leaq    L_.str1(%rip), %rdi
xorl    %eax, %eax
callq   _printf

The value of i is stored in -4(%rbp).

In general constexpr has nothing to do with this issue. Also as was pinpointed by @MarcGlisse, variable length arrays are not part of the standard and this is actually a g++ extension.

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57