The primary consideration when deciding what to put in the for-loop header should be whether the for-loop header conveys the structure of the loop. The three elements (initializer; condition; update) should form a coherent story.
I would express your function like this:
public string Reverse(string s)
{
char[] arr = s.ToCharArray();
for (int i = 0, j = s.Length - 1; i < j; ++i, --j)
{
char swap = arr[i];
arr[i] = arr[j];
arr[j] = swap;
}
return arr.ToString();
}
From just the for-loop header, a reasonably experienced programmer can recognize the idiom for stepping two array indices until they meet in the middle. By convention, i
and j
are array indices; you don't need the …Idx
Hungarian suffix.
In comparison, the interviewer's proposal looks unstructured. I feel like I have to mentally decompile it back into the for-loop above to understand what is going on.
I've also renamed temp
to swap
as a silent "comment".
You might be wondering, to what extreme can you pack logic into the for-loop header? In practice, I've never seen more a good for-loop header that involved more than two variables. The probable explanation is that the condition usually involves a binary comparison operator. A third variable would therefore usually be "off-topic" for the header.
Two other guidelines you might want to use are:
- If you can fill in all three parts of the header (initializer; condition; update), then a for-loop is probably appropriate.
- If the loop body surreptitiously updates the iteration variable, such that the header istells a misleading or incomplete story, then the iteration should probably not be done using a for-loop.