在遞歸函數中因不正確使用公共變量而形成死循環
昨天碰到了挺郁悶的錯誤,我寫的一個遞歸函數,形成了死循環。代碼如下:
1
2
'遞歸刪除頻道,參數:頻道ID
3
Sub DeleteBoard(bid)
4
'刪除該頻道所有新聞
5
News.DeleteByCondition "BoardID=" & bid
6
'刪除該頻道所有子頻道
7
Dim bs
8
bs = Board.GetList("FartherID=" & bid, false, -1, -1)
9
If IsArray(bs) Then
10
For i=LBound(bs) To UBound(bs)
11
DeleteBoard bs(i).ID
12
Next
13
End If
14
'刪除該頻道
15
Board.Delete bid
16
End Sub
17
后來檢查才發現,罪魁禍首就是那個i,它是一個全局變量。遞歸的時候,在另一次調用的時候,會修改它的值……因而,就莫明其妙的形成了死循環。修改后代碼如下:

2
'遞歸刪除頻道,參數:頻道ID3
Sub DeleteBoard(bid)4
'刪除該頻道所有新聞5
News.DeleteByCondition "BoardID=" & bid6
'刪除該頻道所有子頻道7
Dim bs8
bs = Board.GetList("FartherID=" & bid, false, -1, -1)9
If IsArray(bs) Then10
For i=LBound(bs) To UBound(bs)11
DeleteBoard bs(i).ID12
Next13
End If14
'刪除該頻道15
Board.Delete bid16
End Sub17

1
2
'遞歸刪除頻道,參數:頻道ID
3
Sub DeleteBoard(bid)
4
'刪除該頻道所有新聞
5
News.DeleteByCondition "BoardID=" & bid
6
'刪除該頻道所有子頻道
7
Dim bs, i
8
bs = Board.GetList("FartherID=" & bid, false, -1, -1)
9
If IsArray(bs) Then
10
For i=LBound(bs) To UBound(bs)
11
DeleteBoard bs(i).ID
12
Next
13
End If
14
'刪除該頻道
15
Board.Delete bid
16
End Sub
17
增加了i的內部聲明,這樣,就會使用內部的i,而不是全局的那個。

2
'遞歸刪除頻道,參數:頻道ID3
Sub DeleteBoard(bid)4
'刪除該頻道所有新聞5
News.DeleteByCondition "BoardID=" & bid6
'刪除該頻道所有子頻道7
Dim bs, i8
bs = Board.GetList("FartherID=" & bid, false, -1, -1)9
If IsArray(bs) Then10
For i=LBound(bs) To UBound(bs)11
DeleteBoard bs(i).ID12
Next13
End If14
'刪除該頻道15
Board.Delete bid16
End Sub17

我不相信神話,我只相信汗水!我不相信命運,我只相信雙手!

浙公網安備 33010602011771號