[英]What does it mean when the stopping condition of a for loop is a lone pointer variable?
我遇到了一個for循環,其中條件是參數(p)本身。 循環何時停止? 我的C ++書中沒有這種情況。
for (PDFS *p = e->prev ; p ; p = p->prev) {
push_back (p->edge);
edge[p->edge->id] = vertex[p->edge->from] = vertex[p->edge->to] = 1;
}
當p
為NULL
時,循環將停止。 在循環中,您不需要顯式檢查條件p !=NULL
,或者在C ++ 11中, p != nullptr
。
使用空終止的c字符串時,也會編寫類似的代碼:
char str[] = "its null-terminated string";
for(size_t i = 0 ; str[i] ; ++i)
std::cout << str[i] << std::endl;
在這種情況下,您不需要檢查條件i < strlen(str)
或類似的東西。
當p
為NULL
或0
時,它將停止。
當p->prev
沒有指向另一個元素時,會發生這種情況。
當p指針等於NULL指針時將停止
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.