Quick question on for loops header

I keep forgetting how this works:

1
2
3
4
5
 for (T<ItemType>* tempPtr = headPtr; tempPtr; tempPtr = tempPtr->getNext())
        {
            if (tempPtr->getItem() == newInput)
                throw DuplicateItemError();
        }


So in the header after initialization, "tempPtr;" is this just saying run this loop while this pointer is true?
In other words, this for loop will run regardless because tempPtr will always be true since we initialized it in the first part of the for loop?

I have seen other short methods of writing loops or returns and it just amazes me and I get confused that it can be so short.
Last edited on
jetm0t0 wrote:
is this just saying run this loop while this pointer is true?

Yes, that's essentially what it's saying. When you use a pointer where a boolean expression is expected null will be treated as false and all other pointers (i.e. pointers that point to something) will be treated as true.

In other words, it's equivalent to:
 
for (T<ItemType>* tempPtr = headPtr; tempPtr != nullptr; tempPtr = tempPtr->getNext())


jetm0t0 wrote:
In other words, this for loop will run regardless because tempPtr will always be true since we initialized it in the first part of the for loop?

My guess is that tempPtr->getNext() will return a null pointer when you have reached the end which will cause the loop to stop.

If the list is empty headPtr will probably be null which will cause the loop to stop right away, before running a single iteration.
Last edited on
Oh that's awesome, and powerful! It really is count controlled secretly the whole time. Because we can start at whatever headPtr is and then keep going until it sees a nullptr. wow. I am used to seeing things more obviously set as an integer to work with.
Topic archived. No new replies allowed.