Iterating the task list

The next step is to iterate the list from the first link following each pNext pointer until we get to the end of the list. For each link accessed, the task should be executed. Start by writing a function that performs the execution by printing out the description of the task and then returning a pointer to the next task. Just above the main function, add the following code:

    task *execute_task(const task* pTask) 
{
if (nullptr == pTask) return nullptr;
cout << "executing " << pTask->description << endl;
return pTask->pNext;
}

The parameter here is marked as const because we will not change the task object pointed to by the pointer. This indicates to the compiler that if the code does try to change the object there is an issue. The first line checks to make sure that the function is not called with a null pointer. If it was then the following line would dereference an invalid pointer and cause a memory access fault. The last line returns the pointer to the next link (which could be nullptr for the last link in the list), so that the function can be called in a loop. After this function, add the following to iterate the entire list:

    void execute_all() 
{
task* pTask = pHead;
while (pTask != nullptr)
{
pTask = execute_task(pTask);
}
}

This code starts at the beginning, pHead, and calls execute_task on each link in the list until the function returns a nullptr. Add a call to this function towards the end of the main function:

        execute_all(); 
destroy_list();
}

You can now compile and run the code. The result will be:

    executing remove old wallpaper
executing fill holes
executing size walls
executing hang new wallpaper
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset