FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!

D Programming Language -- a simple example




Based on a .txt file I want to be understandable to novice programmers. Comments on how to make it more understandable, while being faithful to the original forum thread, are welcome. This could get pretty long if I continue to add annotation for every post in the original thread!

How to loop for each element of an enumerated constant in D

PS. This file contains long lines. Enable word wrap to view it easily.
-- Option "enable text wrapping" or "enable word wrapping".
-- Print preview may work without changing any options.
-- Most word processors wrap by default; most text editors don't.

Original discussion:

http://forum.dlang.org/thread/k080v5$4pv$1@digitalmars.com

I would like to annotate this, suitable to a newcomer to the language, possibly even for a beginning programmer.

Alexandr Druzhinin:

"
Quote:
Hello all.
I have some enum foo { first=1, second=2, fourth=4, sixth=6} and I'd
like to go through this enumeration like it:
foreach(m; foo.min..foo.max) {
bar(m);
}
But without excluding foo.max and correct handle situation when enum
identifiers aren't consequentive.

Thanks in advance
"

He wants foo to be a collection of named constants. foo is a type, not a variable. A variable of type foo can be declared as:

foo f; // f will be one of first, second, fourth, or sixth
Constants foo.first, etc. can be used anywhere in the program. These values can be stored into an int variable, but only with a cast:

int i = cast(int)foo.fourth; // i will be set to four
(note: in C, enumerated constants are of type int; in D they are unique)

Variables in D will be automatically typed if the type can be determined from context. It is customary in D to declare variables as "auto" to let the compiler figure out the type. Because of the cast to int, "auto i" would result in i being an int. Remove the cast, and "auto i" would cause i to be type foo.



0 blog comments below




FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.