ループ出口条件とは、1 つのループ実行の反復回数を決める条件のことです。for ループの場合は、固定インデックスによって反復回数が決まっています。ループの反復回数は数えられるものでなければなりません。つまり、反復回数を指定するときは次のいずれかを使用しなければなりません。
定数
ループ不変項
最外ループ添字の線形関数
ループ出口が計算に依存する場合、ループは可算ではありません。以下の例は、可算/不可算ループの構造を示しています。
例: 可算ループ |
---|
void cnt1(float a[], float b[], float c[], int n, int lb) { // Exit condition specified by "N-1b+1" int cnt=n, i=0; while (cnt >= lb) { // lb is not affected within loop. a[i] = b[i] * c[i]; cnt--; i++; } } |
次の例は、異なる可算ループ構造を示しています。
例: 可算ループ |
---|
void cnt2(float a[], float b[], float c[], int m, int n) { // Number of iterations is "(n-m+2)/2". int i=0, l; for (l=m; l<n; l+=2) { a[i] = b[i] * c[i]; i++; } } |
次の例は、カウント値が異なる依存性ループであるために不可算のループ構造を示しています。
例: 不可算ループ |
---|
void no_cnt(float a[], float b[], float c[]) { int i=0; // Iterations dependent on a[i]. while (a[i]>0.0) { a[i] = b[i] * c[i]; i++; } } |