Deep C Dives: The Brilliant But Evil for |
Written by Mike James | |||||
Tuesday, 19 November 2024 | |||||
Page 4 of 4
The Evil PartsThe for is a flexible construct capable of being used to implement for loops and a range of different conditional loops. As such it is not a nice simple straightforward enumeration loop and is capable of great misuse. As each part of the for loop can be an expression, the possibilities are great. For example, you can use three functions to control the loop: for(init();test();inc()){ and obviously init performs the initialization, test returns a Boolean to control the loop and inc is evaluated at the end of the loop. In this form it is clear that the for loop can do almost anything and implement almost any type of loop with an exit point at the start. In most cases it isn’t even necessary to resort to using functions to introduce statements into the mix. Often you can get away with just using expressions separated by a comma operator. For example: for(i = 1,j = 9;j > 0;i++,j--){ printf("%d %d ", i, j); } Notice that we initialize both i and j and that i increments and j decrements each time through the loop. The result is a loop in which i runs from 1 to 9 and j from 9 to 1. There are alternative, clearer, ways of writing this loop. Final ThoughtsC for loops aren’t really enumeration loops and probably shouldn’t have “for” in their name. In practice, they encompass a wide range of loop types and as such they are dangerous from the point of view of code clarity. You will encounter many robust opinions that this form of loop or that form of loop is evil and should be avoided, and some are. However, what matters, and it matters in all code not just the for loop, is clarity of intent. If a for loop is a good expression of what you intend it to do, then it is a good for loop, no matter what anyone else says. One way to ensure that this is the case, without having to spend too much time on evaluation, is to restrict yourself to only a small number of variations - for(i = 0;i < n;i++) is good. Deep C Dives
|
|||||
Last Updated ( Tuesday, 19 November 2024 ) |