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.
In C standard, C11
, chapter §6.8.5, Iteration statements, it is listed
iteration-statement:
while (
expression) statement
do
statementwhile (
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With