The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Linked lists The Fundamental Ambiguity Theorem | ||
The Fundamental Ambiguity Theorem
There is a part of printBackward that might have raised an eyebrow: Node *head = list;Node *tail = list->next; After the first assignment, head and list have the same type and the same value. So why did I create a new variable?
The second assignment creates a new reference to the second node in the list, but in this case we think of it as a list. So, even though head and tail have the same type, they play different roles. This ambiguity is useful, but it can make programs with lists difficult to read. I often use variable names like node and list to document how I intend to use a variable, and sometimes I create additional variables to disambiguate. I could have written printBackward without head and tail, but I think it makes it harder to understand: void printBackward (Node *list) {if (list == null) return; printBackward (list->next); cout << list->cargo; } Looking at the two function calls, we have to remember that printBackward treats its argument as a list and print treats its argument as a single object. Always keep in mind the fundamental ambiguity theorem: A variable that refers to a node might treat the node as a single object or as the first in a list of nodes.
|
||
Home Linked lists The Fundamental Ambiguity Theorem |