Syntax Preference

snarfblam

Ultimate Contributor
Joined
Jun 10, 2003
Messages
2,097
Location
USA
I have a feeling that this will depend on whether you program C# or VB, but...

I'm sure most C# programmers have noticed that C#'s for syntax is a bit more involved that that of VB. If a new, more VBish loop structure was introduced, which of the following would you prefer, and why? I'd appreciate other suggestions, too, but understand that the basic idea is to compliment VB's simple "For blah = blah To blah" syntax.


Code:
loop(controlVariable, start, lastValueIterated){}
 
[COLOR=DarkGreen]//Compare[/COLOR]
loop(i, 5, 10) {}
for(int i = 5; [COLOR=Red][B]i <= 10[/B][/COLOR]; i++) {}

[COLOR=Blue]5, 6, 7, 8, 9, 10[/COLOR]
Code:
loop(controlVariable, start, terminatingValue){}
 
[COLOR=DarkGreen]//Compare[/COLOR]
loop(i, 5, 10) {}
for(int i = 5; [COLOR=Red][B]i < 10[/B][/COLOR]; i++) {}

[COLOR=Blue]5, 6, 7, 8, 9[/COLOR]
Code:
loop(controlVariable, start, iterationCount){}
 
[COLOR=DarkGreen]//Compare[/COLOR]
loop(i, 5, 10) {}
for(int i = 5; [COLOR=Red][B]i < 5 + 10[/B][/COLOR]; i++) {}

[COLOR=Blue]5, 6, 7, 8, 9, 10, 11, 12, 13, 14[/COLOR]

And just in case anyone really wants to know why I'm asking, I am working on a command interpreter, and for immediate execution, small and simple goes a long way.
 
I think since all three are so different from the traditional (init, condition, step) style loop and because each looping style is fundamentally different in it's own right, any of the three should be fine so long as you fully document it.

I switch between C#, VB, and C++ as well as a few scripting languages so maybe I'm just used to all the looping structures. Out of all of them, the inclusive for statement in VB drives me nuts, though. Of course, array indexing in VB drives me nuts in general so I guess it's just a counting problem. My personal preference would be not 1 because it's not what I would normally do if I were indexing a for statement.

What VB does:
Visual Basic:
Dim super as New ArrayList()
super.Add(1)
super.Add(2)
super.Add(3)
'
For Dim i As Integer = 0 to super.Count - 1 ''otherwise your overrun the array.  The extra -1 is annoying to me.
   Console.WriteLine(super(i))
Next

What I expect:
C#:
ArrayList super = new ArrayList();
super.Add(1);
super.Add(2);
super.Add(3);

for (int i = 0; i < super.Count; i++) // I use < becuase I know items are at indexes 0, 1, 2 and the list has 3 items in it.
{
   Console.WriteLine(super(i).ToString());
}

Number three is probably the most intriguing to me, probably because it seems the most straightforward: Do X starting at Y, Z times in a row. It seems to be a slightly higher level of abstraction than a regular for statement, though I'm not sure if it's frequency of usefulness would warrant creating it for C#, say. (In other words, do you actually say "I wish I had this feature" enough times to make it worth the effort of adding the feature or would it be used so infrequently that you could get by without it?)
 
Last edited:
That's why I supposed the answer would depend on a user's language of preference. #1 is a VB style loop, comfortable to people who use VB exclusively. #2 is a normal loop, comfortable to anyone who uses something besides VB. And #3 I just threw out there. Throw it into C# and it would probably never get used. It could, possibly, maybe, be a little more useful in a scripting or immediate execution context.

Say you were to display output (a list of files, a summary of a long operation, etc.) twenty lines at a time, something like this...
C#:
function showOutput(string[] lines){
    for(int i = 0; i < lines.Length; i += 20) { // Loop through lines 20 at atime
        for(int j = i, j < i + 20<, j++) { // Show next 20
            if(j < lines.Length) WriteLine(lines[j]);
        }
        WaitForKeyPress();
    }
}
...could be written as...
C#:
function showOutput(string[] lines){
    int i;
    while(i < lines.Length){ // While there are lines left to show
        loop(i, i, 20) { // Show next 20
            if(i < lines.Length) WriteLine(lines[i]);
        }
        WaitForKeyPress();
    }
}
...but the first is a little neater and more to the point. In other words, loop(x, x, y) would be a convinient way to say "take the next y items," and without the need to manage a second control variable. Nifty, but I'm not sure how useful.
 
I would like something like:
Code:
loop(iterationCount, [controlVariable], [start=0]){}
Where you can choose to leave out the control variable and/or the start value. After all, often you just want to say 'do this n times', without needing a counter variable.
 
I have considered the situation, and regardless of which of the loop constructs I implement, chances are that there will be optional parts to the loop. For example, take loop construct #3 from my original post. We could enhance it as so...
Code:
[color=DarkGreen]
// loop([[i]controlVariable[/i], [[i]start[/i], ]] [i]iterationCount[/i]) {}
// default value for [i]start[/i] would be 0.
// default value for [i]controlVariable[/i] would be an unnamed hidden variable.

// Giving us the ability to write code like the following:
[/Color]
[COLOR=Blue]loop[/COLOR](10) {
    [Color=DarkGreen]// Show static message 10 times[/Color]
    [COLOR=DarkRed]MessageBox[/COLOR].Show("0123456789");
}

[COLOR=Blue]loop[/COLOR](i, 10) { [Color=DarkGreen]// 10 iterations = 0 to 9[/Color]
    [Color=DarkGreen]// Show numbers 0 to 9[/Color]
    [COLOR=DarkRed]MessageBox[/COLOR].Show(i.ToString());
}

[COLOR=Blue]loop[/COLOR](i, 1, 10) {[Color=DarkGreen]// 10 iterations starting at 1 = 1 to 10[/Color]
    [Color=DarkGreen]// Show numbers 1 to 10[/Color]
    [COLOR=DarkRed]MessageBox[/COLOR].Show(i.ToString());
}

Frankly, the more and more I program, the less and less I find myself doing a loop where a control variable isn't necessary. Of the top of my head I can't really see when this would be particularly useful (I'm not saying it wouldn't be, if you have an example, I'd love to see it, if for no other reason than out of curiousity).

The idea is that the real treat would be something like this:
C#:
for(int i = 0; i < value.Length; i++){
    MessageBox.Show(values[i]);
}
// BECOMES
loop(i, values.Length) {
    MessageBox.Show(values[i]);
}
I know that C# has a foreach loop. We aren't really talking C# here, though, but rather my own command interpreter syntax.
 
Yes, that is exactly what I had in mind, offering those 3 possibilities.

The usefulness of a loop(iterationCount) might depend on the application domain - I can see it popping up more often in games e.g. - but I agree it's probably rather marginal.
 
marble_eater said:
...if you have an example, I'd love to see it...
A comand shell is a pretty good example:
C#:
 //This comes from [url=http://people.clarkson.edu/~jnm/os/homework/shell/]here[/url] and is actually C-style psuedo code, not C#
int main (int argc, char **argv)
     {
	while (1){
		int childPid;
		char * cmdLine;

	        printPrompt();

	        cmdLine= readCommandLine(); //or GNU readline("");

		cmd = parseCommand(cmdLine);

		record command in history list (GNU readline history ?)
 
		if ( isBuiltInCommand(cmd)){
		    executeBuiltInCommand(cmd);
		} else {		
		     childPid = fork();
		     if (childPid == 0){
			executeCommand(cmd); //calls execvp  
			
		     } else {
			if (isBackgroundJob(cmd)){
			        record in list of background jobs
			} else {
				waitpid (childPid);

			}		
		    }
	        }
     }
I guess any sort of event loop really would be a good example.
 
Maybe I should clarify what I meant about the control variable. There are plenty of times you might use a While loop without a control variable, but in terms of a for-style loop, usually (probably almost always) the loop will contain dynamic code that depends in the iteration number. How often do we find ourselves repeating a completely static task?

Either way, the option will be there to loop with no control variable.
 
marble_eater said:
How often do we find ourselves repeating a completely static task?
You make a valid point. I too could only come up with silly stuff that you wouldn't actually do (like a row of stars to the screen and other tasks which can be done more easily and efficiently another way).
 
Back
Top