Page 1 of 4 The C for loop has taken over the world. You have to look hard to find a language that doesn't use it or something very similiar - but why? Find out more in this extract from my latest book, Deep C Dives: Adventures in C.
Deep C Dives Adventures in C
By Mike James
Buy from Amazon.
Contents
Preface Prolog C Dive
- All You Need Are Bits
- These aren’t the types you’re looking for
- Type Casting
- Expressions
- Bits and More Bits
- The Brilliant But Evil for ***NEW!
- Into the Void
- Blocks, Stacks and Locals
- Static Storage
- Pointers
- The Array and Pointer Arithmetic
- Heap, The Third Memory Allocation
- First Class Functions
Extract: First Class Functions
- Structs and Objects
- The Union
- Undefined Behavior
- Exceptions and the Long Jump
<ASIN:B0D6LZZQ8R>
Dive 6
“We all know Linux is great...it does infinite loops in 5 seconds.”
Linus Torvalds
If you need proof that C is a machine independent assembler, look no further than the for loop. It is closer to the metal than a for each or for in loop found in other languages and yet it has been deeply influential. So much so that the C for loop has made its way into Java, JavaScript, Go and many other higher-level languages.
The C for loop is brilliant in that it allows many “creative” uses of the construct and it is evil for exactly the same reason. More accurately it fails to capture the fundamental idea of an enumeration.
Quick Guide To The Loop Zoo
In the early days of programming we created loops to repeat instructions. This was a largely ad-hoc affair and not many stepped back from the code face to consider what was going on. Later we could consider the whole idea of repeating something and how many different varieties of loop there actually are and are actually needed.
The first big distinction is between the enumeration and the conditional loop. An enumeration loop is simply doing something a given number of times. Sometimes the number of times is implied by the number of things to process, e.g. the number of items in a data structure that need examining. Pure enumeration loops are often written as for loops of varying abstraction:
for i=1 to 10
for each x in array
for each value in 1 to 10
and so on.
Some languages even have enumeration loops like:
repeat 10 times
although this form isn’t particularly flexible.
The alternative to an enumeration loop is the conditional loop which repeats something until a condition is satisfied. You can tell the difference between the two loops by asking the simple question “do you know how many times the loop will repeat before the loop starts?”. If you know that the loop will repeat x times before it even starts then you have an enumeration loop.
Even when you do have an enumeration loop it is sometimes easier to write it as a conditional loop.
|