The title says it all. Why is stdout not compile-time constant? Why is this fine
int main() {
const FILE *fp = stdout;
}
but not
const FILE *fp = stdout;
int main() {
}
Shouldn't both fail, if its not compile-time constant?
Say I'm writing a logging util and I want to make stdout my default output stream, how can I do that (without initial setup function call)
struct config {
FILE *this_should_be_stdout;
};
struct config conf = {
.this_should_be_stdout = stdout
}
That is correct behaviour, since stdout is not a constant. The reason it works inside main is that the stdout variable is effectively "brought into existence" during the start-up of main. By that, I mean the variable itself exists but the actual connection to a stream (initialisation) happens at some point before main starts executing.
The reason why this is flagged as an error can be seen in C17 6.7.9 Initialization §4:
All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literal.
Since stdout is neither of those things, and variables at file level are static storage duration, the former cannot be used to initialise the latter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With