FEB
22
2004
|
Playing with the Switch and Foreach StatementsI've been thinking about C's control statements (if, while, switch, for etc) for a little while, and I think there's some room for improvements in the later two... void test(int a) { switch (a) { case 0: Console.WriteLine("blabla"); break; case 1: Console.Write("More "); goto case 0; case 2: case 3: Console.WriteLine("lalala"); break; } } I think forbidding implicit fall-through is a good idea, it avoids void test(int a) { switch (a) { case 0: Console.WriteLine("blabla"); case 1: Console.WriteLine("More"); goto case 0; case 2: case 3: Console.WriteLine("lalala"); } } Something that I am missing all the time is a way to describe value void test(int a) { switch (a) { case <0: System.out.println("a is negative"); case 0: System.out.println("a is 0"); case >0, <=100: System.out.println("a is between 1 and 100"); case <200: case >500, <600: System.out.println("a is >100 and <200, or >500 and <600"); default: System.out.println("a has some other value"); } } Allowing comma-separated lists of operator plus constant makes switch much more
Over the last years most C-based languages got a foreach statement to int sum = 0; foreach (int i in someArray) sum += i; ... and ECMAScript (JavaScript): var sum = 0; for (var i in someArray) sum += i; ... and Java 1.5: int sum = 0; for (int i: someArray) sum += i; I definitely prefer Java's syntax as 'for' is shorter than 'foreach' for (int i = 0; i < 100; i++) System.out.println("Bla"); can be expressed with a foreach loop and a special object that for (int i: new Range(100)) System.out.println("Bla"); It's looking nicer without the new keyword, as shown here: for (int i: Range(100)) System.out.println("Bla"); Using other constructors it would be possible to specify at start value, to for (int i: Range(50, 10, -1)) System.out.println("i=" + i); As for loops are pretty common, it may make sense to have a special for (int i: 0...99) System.out.println("i=" + i); The expression 'a...b' is short for '(a<=b)?Range(a, b+1):Range(b, a-1, -1)'. void print10Numbers(List numberList) { for (int i: numberList[0...9]) System.out.println("i=" + i); } Unlike regular methods for slicing collections such as Java's List.subList()
|
![]() |