Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a loop?

Tags:

c

loops

semantics

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.

like image 802
Victor Brunell Avatar asked Jan 05 '23 17:01

Victor Brunell


2 Answers

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.

like image 161
Sourav Ghosh Avatar answered Jan 10 '23 20:01

Sourav Ghosh


In a sense, yes it is a loop, but in reality no. It is technically a loop because you are using loop syntax, but what you're actually doing is just running the code in your "loop" once, and then breaking. I wouldn't really count it as a loop because you're not adding any algorithmic runtime to your program, so there's no point in counting it as a loop. Note: don't do this, it is pointless and bad coding practice.

EDIT: Credits to Jeremy in the comments below, there is at least one case where this construct can be useful in C: do { ... } while (0) — what is it good for?

like image 28
Andrew Avatar answered Jan 10 '23 19:01

Andrew