I’ve been told that if I’m coding in ANSI C to declare in the order that the variables will be used, assert that pointers are not null and that indices are within bounds, and to initialize just before usage of the variable.
If I declare a const can I initialize it after a block of assertions and code?
In Java final initializations must occur at declaration, yet is it consistent through ANSI C implementations that I can initialize a const once, but not necessarily at the time of declaration?
The Java compiler has a small amount of flow logic to allow you to initalise
finalvariables after their declaration. This is legal Java:Java will detect if any branches leave the final value undefined. It won’t analyse the conditions, so this is not legal Java, even though it’s logically similar:
In ANSI C89,
constvariables ( other thanextern) must be initialised in the statement they are declared in.The
externmodifier on a declaration tells the compiler that the variable is initialised in a different complation unit ( or elsewhere in this compilation unit ).In ANSI C99, you can mix declarations and code, so you can declare and initialise a
constvariable after a block of assertions and code. Portability of 1999 ANSI C remains an issue.A work around for C89 is to note that the rules for declarations preceding code work at block scope rather than function scope, so you can do this: