DEV Community

Discussion on: What is the simplest code to explain a loop?

 
slavius profile image
Slavius • Edited

In for loops you can empoy this little trick to emphasize decrementing from max to 0:

int max = 10;
for (i = max; i --> 0;) {
  printf(".");
}

It is just pretty-formatted i-- > 0
What it does it decrements i and makes sure it's > 0 in the comparison part of the for leaving out the increment/decrement part.
Works the opposite way (end to start) so it's not suitable for processing lists where ascending order matters.

Thread Thread
 
alchermd profile image
John Alcher

That's a neat trick! But it looks something more of a trick to get the shortest solution to a programming quiz rather than a practical solution, IMO.

Thread Thread
 
slavius profile image
Slavius

Let's call it a syntactic sugar. It makes the code shorter, more visual while still keeping the same functionality; but may make someone puzzled about what it does on first sight as it's not common.