简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM