final variables

Jeremie Pelletier jeremiep at gmail.com
Mon Sep 21 18:41:15 PDT 2009


#ponce wrote:
> Is there a need for final variables now that we have immutable and const in D2 ?
> 
> 
> This program does not compile: 
> import std.stdio;
> 
>  int main(char[][] args)
> {
> 	final int a = 4;
>         a = 8;
> 	writefln("%s", a);
> 	return 0;
> }
> 
> But the following program does run: 
> 
> import std.stdio;
> 
>  int main(char[][] args)
> {
> 	final int a = 4;
> 	final int* p = &a;
> 	*p = 8;
> 	writefln("%s", a);
> 	return 0;
> }
> 
> and prints 8. 
> 
> So final for variables seems weaker than C const.
> Another problem is that final looks like Java :)

Strange, I cannot compile both of your examples in D2.032 without 
getting "final cannot be applied to variable".

final is intended for classes which may not be further subclassed.

const work just fine in D and even better than C's const in my opinion. 
I like being able to declare only a part of a type as const, such as 
const(int)[], const(void)* or const(immutable(char)[])[]. I cannot tell 
about D1's const however, its been so long since I last used it.


More information about the Digitalmars-d-learn mailing list