30

for(i = 0; i < n; i++);//<-- this one
{
//Do stuff
}

One day struggling why this for loop in C just iterates once, found out that ";" was leaving the for body empty, and the "Do Stuff" ended beign out of the for.

Comments
  • 3
    Well ya... ";" Typically terminates a statement so it's looping but not accessing the curly brackets.
  • 0
    Ouch :)
  • 2
    Looks like someone experienced one too many nights hunting for a missing ; and decided to overcompensate.
  • 2
    I think most compilers will warn about that with -Wall, but I may be mistaken
  • 2
    @DrEmann with C language I know you can do a while loop spin lock like this. The classic semaphore example; while(flag); causes a thread to wait in place until another thread/activity sets flag to false. So I think it would work with a for loop
  • 0
    @Lisanna this happened to me too. But I fail to see why this is semantically the same as do nothing once? Would declaring the flag volatile force the compiler to not optimize it away?
  • 0
    @Lisanna never said it was a good example, just used it as an example of putting a semicolon right after some sort of loop
  • 0
    @Lisanna Classic as in it's generally how the concept of a semaphore is taught ;3 most sites/textbooks will often use a simple while loop lock to show the idea behind the waiting
Add Comment