问题
Say I have a file, window.h, which defines:
extern const int window_width, window_height;
I don't want anyone to change these variables, so they're const for all includers of window.h. However, is it legal to declare them non-const in the source file?
// window.c
int window_width, window_height;
void onResizeWindow(int w, int h) {
window_width = w;
window_height = h;
}
This compiles without linker errors for me in Apple clang version 12.0.0 (clang-1200.0.22.7). But is it legal and well-defined C?
回答1:
No, it is undefined behaviour. Two declarations for the same object must have compatible types, and a non-const
-qualified type is not compatible with the const
-qualified version of the same type. (Like other issues which involve two or more translation units, this undefined behaviour does not require a diagnostic. But the absence of a diagnostic message doesn't mean that it's OK. It just means that the compiler only looks at one translation unit at a time, so it can't see inconsistencies.)
It is not an error to use a pointer to a const
-qualified type to access a non-const
object of that type, or even to use a pointer to a non-const
qualified type to read from (but not mutate) a const
-qualified object. But be aware that as long as the actual definition of the variable is not const
-qualified, it is also not an error to "cast away const
" from a pointer and use it to modify the variable.
来源:https://stackoverflow.com/questions/63525933/is-it-legal-c-to-declare-a-non-const-variable-const-externally