ccompilationstacklanguage-lawyerc11

Can a C compiler legally reject a program if its call stack depth exceeds a fixed limit at compile time?


I've read that C doesn't mandate a minimum stack size, leaving it implementation-defined. But could a conforming C compiler refuse to compile a program if it detects--say, through static analysis--that the call stack depth (e.g., from nested function call) exceeds a fixed limit it supports? Or is this always a runtime issue? I'm curious if the C standard (like C11 or C23) allow rejecting valid syntax at compile time based on stack depth alone, assuming no recursion or undefined behaviour


Solution

  • The C standard is only concerned about limitations during compilation, meaning things like the amount of nested blocks in the source code. It does not mention hardware-related things like stack memory or call stack depth. Some of the more exotic targets which can you can write C code for don't even have a stack.

    A conforming C compiler is only required to give diagnostic messages for constraint and syntax violations. There is nothing in the standard preventing a C compiler for doing extra diagnostics beyond that. And so compilers also tend to give messages for other forms of violations: semantics, explicit undefined behavior etc, but none of that is required by the standard.

    Things like running out of memory at compile-time is rather the linker's business and linkers do tend to give diagnostics about that. But linkers aren't really covered by the C standard at all.

    Similarly, the C standard does not state what will happen to an executable in case there were diagnostic messages during compilation, regardless if the messages were about non-conformance or something else.