I know that unused variables in C typically just lead to compiler warnings, and const
variables are meant to be read-only.
However, I’m curious: according to the C standard, is there any scenario where simply declaring a const
variable without ever using it can result in undefined behavior?
I’m not asking about compiler warnings or optimizations — only whether the standard allows this to become undefined behavior in any edge case.
Defining objects (such as variables) that are unused in a program does not constitute undefined behavior (UB). This is because all forms of undefined behavior are explicitly enumerated by the C standard, and unused variables are not among them. Additionally, applying qualifiers like const
or volatile
to these unused objects does not alter this fact.
Furthermore, the C standard does not mandate compilers to issue diagnostics for unused variables, although compilers commonly provide warnings as a convenience to developers.