它有时不仅仅是方便.
这些是等价的:
for (int a = 10; a < 20; a = a + 1) { cout << a << endl; } for (int a = 10; a < 20; ) { cout << a << endl; a = a + 1; }
但是,这些不是:
// this works ... for (int a = 10; a < 20; a = a + 1) { if (blah ...) continue; cout << a << endl; } // this doesn't for (int a = 10; a < 20; ) { if (blah ...) continue; cout << a << endl; a = a + 1; }
因为你是来自python,一个惯用的 for循环就像一个python range
,但更强大.用Cthon表示的C for循环将是:
for a in range(10,20,1)
将此表达为以下内容更为惯用:
for (a = 10; a < 20; a += 1)
因为循环增量是1
,所以这样做更加惯用:
for (a = 10; a < 20; ++a)
但是,for循环是:
for ([init_stmt]; [test_stmt]; [incr_stmt])
任何*_stmt都可以复合:
for (x = 0, y = 0; x < 10; ++x, y += 2)