mercredi 11 novembre 2020

Array index (/dimension) mandatory constexpr [duplicate]

I'm reading Lippman et.al 5/e

In sec. 3.5.1, the book goes to say ...

dimension must be known at compile time, which means that the dimension must be a constant expression.

I doubted the correctness of the above statement, so I tried the following,

#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {
    size_t N;

    cin >> N;
    int arr[N]{};

    for (const int &elem: arr)
        cout << elem << " ";
    cout << endl;

    return 0;
}

$ make
g++ -g -Wno-unused-variable -Wno-unused-but-set-variable -std=c++11 -Wall -c test.cpp
g++ -g -Wno-unused-variable -Wno-unused-but-set-variable -std=c++11 -Wall test.o -o test
$ ./test 
12
0 0 0 0 0 0 0 0 0 0 0 0 
$ 

I don't think N is a constexpr, but it works.

Am I doing something wrong ?

Please help me clarify the confusion.

Aucun commentaire:

Enregistrer un commentaire