23
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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で脱出できるという訳。

23
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
23
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?