カンマ区切りの式

comp.lang.c++.moderated - Top 20 C++ Tips of All Time?


for文でカンマ区切りの式を使えるのは有名ですが

int count = 0;
vector<int> v;
typedef vector<int>::iterator Iterator;

for (Iterator it = v.begin(), last = v.end(); it != last; ++it, ++count);


if文やwhile文の条件式にもカンマ区切りの式は使えるようです。
例えばこんな感じです。

#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    int y = 2;

    if (++x, --y) // yが0でなかったら
    {
        cout << x << "," << y << endl;
    }

}
1,1
#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    int y = 10;

    while (++x, --y) // yが0でない間ループする
    {
        cout << x << "," << y << endl;
    }
}
1,9
2,8
3,7
4,6
5,5
6,4
7,3
8,2
9,1


条件式をカンマで区切った場合は、一番後ろの式が条件式として使用されるようです。

#include <iostream>

using namespace std;

int main()
{
    if (false, true)
    {
        cout << "!" << endl;
    }
}
!


けっこう応用できそうな気がします。