The Java compiler has a small amount of flow logic to allow you to initalise final
variables after their declaration. This is legal Java:
final int something;
if ( today == Friday )
something = 7;
else
something = 42;
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:
final int something;
if ( today == Friday )
something = 7;
if ( today != Friday )
something = 42;
In ANSI C89, const
variables ( other than extern
) must be initialised in the statement they are declared in.
const int something = ( today == Friday ) ? 7 : 42;
The extern
modifier 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 const
variable 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:
#include<stdio.h>
int main ( void )
{
printf ( "wibble\n" );
{
const int x = 10;
printf ( "x = %d\n", x );
}
return 0;
}
const int a;
is called a "tentative definition", or something like that. If the variable is later unambiguously defined, then it's treated as just a declaration. If not, it's a definition. So you can haveconst int a;
in a header, and thenconst int a = 12;
in the .c file. Not that you would often want to, since you risk forgetting the definition and ending up witha
being 12 in some compilation units and 0 in others... – Arad