5
4

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.

マクロで見通しのよいイテレーションを

Posted at

次のような for ループがあったとする。

    for (elem = next(set); next(set) != NULL; elem = next(set)) {
        // do something ...
    }

こういうときは次のようなマクロを定義しておくと見通しがよくなる。


#define foreach(elem, set) \
    for ((elem) = next(set); next(set) != NULL); (elem) = next(set))

    foreach (elem, set) {
        // do something ...
    }

個人的には定石かなと思っていて、Cであってもちょっとモダンな感じになるので気に入っている。
この書き方は色々応用が効いて、次のようなマクロを定義してみても面白いかもしれない。


#define foreach_except0(elem, set) \
    for ((elem) = next(set); next(set) != NULL); (elem) = next(set)) \
    if ((elem) != 0)

    foreach_except0 (elem, set) {
        // do something ...
    }

ただしやっぱりマクロに過ぎないので濫用はしないこと。

5
4
0

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?