Why does this work?

I was making a primitive linked list, when I stumbled upon a question.

Why does the following code work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  
	Node * curr;

	Node * head = new Node;
	Node * first = new Node;
	Node * tail = new Node;

	head->data = 1;
	head->next = first;

	curr = head;


	

	first->data = 2;
	first->next = tail;

	tail->data = 3;
	tail->next = NULL;

	while(curr != NULL)
	{	
		
		curr = curr->next;
		if(curr == NULL)
			break;
		cout << curr->data << endl;
	
	}


	system("Pause");

	delete head;
	delete first;
	delete tail;




Specifically this part
1
2
3
4
5
6
7
8
9
10
while(curr != NULL)
{	
		
   curr = curr->next;
   if(curr == NULL)
      break;
  cout << curr->data << endl;
	
}


This prints out 2 and 3, however I am not incrementing curr by an incremental operator (curr++). I was under the impression that I would need an incremental operator to make curr point to the next appropriate address (which is tail). Shouldn't the output be 2 every time.

How does it magically know to move to the tail address without an explicit instruction to do so.

Last edited on
What do you think curr = curr->next; does?
All three nodes head, first and tail are already linked together via the pointer next.
head's next points to first
first'next points to tail
tail'next points to NULL (thus ends).

So by using curr = curr->next;, you get the drill.

Also, by setting a pointer to NULL doesn't mean it points to nothing, it will point to an arbitrarily number that is safe when accidentally messed with.
@cire, HAHA just figured that out when I gave the code a 3rd look.


@hentaiw, thanks for the non-snarky response/ explanation, I appreciate it. Thanks again.
Last edited on
Topic archived. No new replies allowed.