Thread overview | ||||||
---|---|---|---|---|---|---|
|
September 22, 2009 final variables | ||||
---|---|---|---|---|
| ||||
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 :) |
September 22, 2009 Re: final variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to #ponce | #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. |
September 22, 2009 Re: final variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jeremie Pelletier | > 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. |
September 22, 2009 Re: final variables | ||||
---|---|---|---|---|
| ||||
Posted in reply to #ponce | #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 |
Copyright © 1999-2021 by the D Language Foundation