Why does this condition work? (for loop,linklist)

could someone explain to me why the condition for the for loop below (the r->link != NULL) works?
1
2
3
4
5
6
7
8
9
10
11
12
	void linking(int q)
	{
		node *temp = new node(q);
		if (n == NULL)
			n = temp;
		else
		{
			node *r;
			for (r = n; r->link != NULL; r = r->link);
			r->link = temp;
		}
	}

this is my understanding of the code above;
first is 1(so it will be temp) but n is currently null, so n(will be 1).
second is 2(new temp), so this will go through the else part.
r=n means 1 will be r..here is the problem I thought r->link is still null how can it continue on to linking 1->2. ?

the int q is just a loop in main.
expected output - 1 2 3 4 5 6 7 8 9 10
ps: im just trying to understand why the code above works
closed account (48bpfSEw)
your code is not complete! Where is "n" declared?

if "n" is a global value. is it initialized? if not then it contains a random value.
You haven't shown the definition of n, but I have to assume it is:
 
  node * n = nullptr;  // List is empty to start 


line 9: This for loop walks the linked list to find the last node. Note the ; at the end of the line. There is no executable statement that is iterated, other than what is in the for statement itself.

The for loop starts by setting r (curr node) to the global n, which we know is not null. Since there are no statements to execute, the increment expression (third term of for statement) is executed. r is replaced by r->link. r is now pointing to whatever the first node's r->link was pointing to, presumably, the second node and the for loop goes back to the top. R's forward pointer (link) is now checked for null. if not null, the increment expression is used to assign r's next pointer to r, so we're pointing to the next node in the list and the loop continues. If null, there is no next node and r is pointing to the last node of the linked list.

When we reach line 10, r is pointing to the last node in the list.
Line 10 then sets r->link to the new node (temp).
Last edited on
oh I actually missed the " ; " in the for loop. I thought line 10 is a statement for the for loop.
thanks.
oh I actually missed the " ; " in the for loop.

That's a very easy thing to miss, and it's why writing an empy loop like this is a REALLY bad idea. It's better to write like:
1
2
for (r = n; r->link != NULL; r = r->link)
    ;

or
for (r = n; r->link != NULL; r = r->link) {}
or
for (r = n; r->link != NULL; r = r->link); // empty loop
The point is to do SOMETHING to help a reader see that the body of the loop is empty
Topic archived. No new replies allowed.