LoveTW
LoveTW

Reputation: 3832

What does it mean when the stopping condition of a for loop is a lone pointer variable?

I encountered a for loop where the condition is the parameter (p) itself. When will the loop stop? I don't see this case in my C++ books.

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;
}

Upvotes: 1

Views: 207

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

The loop will stop when p is NULL. In the loop, you don't need to explicitly check for the condition p !=NULL, or in C++11, p != nullptr.

The similar code is also written you've null-terminated c-string:

 char str[] = "its null-terminated string";
 for(size_t i = 0 ; str[i] ;  ++i)
        std::cout << str[i] << std::endl;

In this case, you don't need to check for the condition i < strlen(str) or something like that.

Upvotes: 8

Vladimir
Vladimir

Reputation: 170849

It will stop when p pointer will equal to NULL pointer

Upvotes: 1

juergen d
juergen d

Reputation: 204784

It will stop when p is NULL or 0.

This will happen when p->prev does not point to another element.

Upvotes: 2

Related Questions