samedi 29 août 2020

C++ stack array without constant expression [duplicate]

From A Tour of C++

The size of an array must be a constant expression

I can not understand why this compiles and runs without errors

int main() 
{
    int input;
    cin >> input;
    char v[input];
    cout << sizeof(v) << endl;
}

While this doesn't

int value(int value)
{
    for(int i = 0; i < value; i++) {
        value++;       
    }
    return value;
}

int main() 
{
    int input;
    cin >> input;
    char v[value(input)];
    cout << sizeof(v) << endl;
}

Can somebody explain to me why does this happen?

Aucun commentaire:

Enregistrer un commentaire