www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - final variables

reply #ponce <aliloko gmail.com> writes:
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 :)
Sep 21 2009
parent reply Jeremie Pelletier <jeremiep gmail.com> writes:
#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.
Sep 21 2009
parent reply #ponce <aliloko gmail.com> writes:
 Strange, I cannot compile both of your examples in D2.032 without 
 getting "final cannot be applied to variable".
Ok I was using D1. Final for variables must have been removed.
 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.
What I understand is that D1's const force compile-time evaluation whereas D2's don't. Not sure though.
Sep 22 2009
parent bearophile <bearophileHUGS lycos.com> writes:
#ponce:

 Ok I was using D1.
 Final for variables must have been removed.
Good.
 What I understand is that D1's const force compile-time evaluation whereas
D2's don't. Not sure though.
const in D1 is very easy, you can't take the address of a const variable, it's like the enum in D2. Some people say that such kind of const isn't necessary if the linker gets a little smarter. Bye, bearophile
Sep 22 2009