Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C language syntax: if { ... } while(0);

Tags:

c

I am looking at https://github.com/iputils/iputils/blob/s20161105/ping.c and I see from lines 608-713:

if (source.sin_addr.s_addr == 0) {
... // Omitted
} while(0);

Two questions:

  1. How it compiles

  2. What is the value of adding while (0) after if statement

like image 393
ErectCrested Avatar asked Nov 16 '25 08:11

ErectCrested


2 Answers

It's two statements in succession. Entirely equivalent to this

if(/* ... */) {
  // Body
}
while(0) {
  // empty
}

while(0); is just a loop with a single empty statement for a body.

There is no value in adding it after the if. I suspect it's leftover from a previous refactoring, but the git history in that repository does not go that far.

like image 93
StoryTeller - Unslander Monica Avatar answered Nov 18 '25 22:11

StoryTeller - Unslander Monica


  1. It compiles because it is two statements, first

    if (...) { ... }
    

    followed by another statement

    while (0);
    

    i.e. a loop with empty body that is never run.

  2. There is no value. while (0); as a separate statement is utterly useless. do { ... } while (0) is not useless but it is a completely different thing.


Probably the code was refactored from a form that initially used do { ... } while (0) and using breaks to exit the flow early (from the linked question above). Currently the source file does not have any instances of do statement, there are only 3 times that the verb do exists in some strings.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!