LoginSignup
22
19

More than 5 years have passed since last update.

do~while(0)とは何か?

Last updated at Posted at 2015-01-09

do~whileなんて珍しいものをと思いきや、
0なのでループしないという謎ソースがあった。

よくよく聞いてみるとエラー処理などで
一気に抜けたい場合などに使えるテクニックらしい。

こんな感じにしてやると

do_while_0.c
#include <stdio.h>
int main()
{
  int i = 0;
  do {
    if (i == 0) {
      printf("hello world! i=%d\n", i);
      break;
    }
    if (i == 1) {
      printf("hello world! i=%d\n", i);
      break;
    }
    printf("I don't want to run here!\n");
  } while (0);
  return 0;
}

gotoなどを使わなくても囲われたブロックからbreakで脱出できるという訳。

22
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19