News for hackers. Stuff that matters.
Re:Misconceptions about loops in C by nedt on Friday June 28, 2024 @07:41AM (#40819647)
You are writing it differently with the goto. You can do the same with the for loop and it becomes symmetric again

  for (i = 0; i <  n; ++i);
  for (i = n; i >= 0; --i);
(Note: not sure if intended that backward should run more often and include i = n)
Re:Misconceptions about loops in C by trealira on Friday June 28, 2024 @07:48AM (#40819686)
To be symmetric, the loops should read like this:

  for (i = 0; i < n; i++)
  for (i = n; --i >= 0; )
The second one could also be this:

  for (i = n - 1; i >= 0; i--)
I say this because your backwards loop accesses the inclusive range [0, n] while your forwards range accesses [0, n - 1].
Re:Misconceptions about loops in C by torstenvl on Friday June 28, 2024 @08:56AM (#40820173)

  for (i = 0; i <= n-1; i++)
  for (i = n-1; i >= 0; i--)
Re:Misconceptions about loops in C by trealira on Friday June 28, 2024 @09:23AM (#40820391)
Yeah, that way of writing them definitely makes them look more symmetric. You could also do this, though it's a bit less pretty:

  for (i = -1; ++i != n; )
  for (i = n; --i != -1; )
Re:Misconceptions about loops in C by Maxatar on Friday June 28, 2024 @12:01PM (#40821990)
Your post is a good example of how backwards iteration is so error prone and fragile.

Your reverse iteration would result in an out of bounds access as well as unsigned integer overflow which results in an infinite loop.