tacos_tacos_tacos
tacos_tacos_tacos

Reputation: 10585

Why am I limited to an arbitrary small ( array size when initializing an array with a const length in C?

Note: I have seen In C, why can't a const variable be used as an array size initializer? already, but this doesn't quite answer my question (or I am not understanding it fully).

This works:

int main() {
    const long COUNT = 1048106;
    int nums[COUNT];
    return 0;
}

This crashes:

int main() {
    const long COUNT = 1048106000;
    int nums[COUNT];
    return 0;
}

I have read that this is actually an inappropriate use of const to begin with (since it means read-only, not evaluated at compile time).

So I am happy to use #define or whatnot instead, but still, it bothers me why this works for some lengths but not but not any higher.

Upvotes: 0

Views: 49

Answers (1)

Both your array declarations are in fact variable length array declarations. COUNT is not a constant expression in C, despite being const.

But regardless, the bigger size simply exceeds your implementation's limits, overflowing the call stack where those locals are usually allocated. Though I suspect this behavior will go away should you compile with optimizations. A compiler can easily deduce that nums isn't used in your snippet, and remove it entirely.

Upvotes: 3

Related Questions