Search code examples
cloopssemantics

Is this a loop?


Is this a loop, not a loop, or both a loop and not a loop? If you're counting the number of loops in a program, would you count this?

do {
   ...
}while(0);

I'm curious because I'm working with someone who has a project that requires him to count the number of loops in a program.


Solution

  • In C standard, C11, chapter §6.8.5, Iteration statements, it is listed

    iteration-statement:

           while ( expression ) statement
           do statement while ( expression ) ;
           for ( expression opt ; expression opt ; expression opt ) statement
           for ( declaration expression opt ; expression opt ) statement

    The do statement while ( expression ) ; is mentioned, so yes, it is a loop (iteration) statement, irrespective of the number of iterations it make in a particular implementation/usage.

    FWIW, this loops one time.

    To add some more clarification, quoting from Wikipedia, (emphasis mine)

    A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code "inside" the loop (the body of the loop, shown below as xxx) is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely.