user1128516
user1128516

Reputation: 53

Operator -> doesn't work as expected in C++

I was practicing single linked list in c++ (practicing how to find the beginning node of the circular list), but found the use of operator -> very confusing. I'm using Visual studio 2010 C++ Express

This works perfectly: head->append(2)->append(3)->append(4)->append(5)

But this doesn't work (to create a circular linked list): head->append(2)->append(3)->append(4)->append(5)->append(head->next)

When I jump in this method and debug, it seems head->next is not passed correctly into the method.

But this works:

  1. Node* tail=head->append(2)->append(3)->append(4)->append(5); tail->append(head->next);
  2. Or after I change return c->next to return head in the two methods, head->append(2)->append(3)->append(4)->append(5)->append(head->next) also works.

What am I missing here? Thank you!

Details of my code is as follows:

void main(){
    Node* head=new Node(1);
    Node* tail=head->append(2)->append(3)->append(4)->append(5)->append(head->next);
    cin.get();
}

class Node{
public:
    Node* next;
    int data;
    bool marked;

    Node(int d){
        data=d;
        marked=false;
        next=NULL;
    }

    Node* append(int d){
        Node* c=this;
        while(c->next!=NULL){
            c=c->next;
        }
        c->next=new Node(d);
        return c->next;
    }

    Node* append(Node* n){
        Node* c=this;
        while(c->next!=NULL){
            c=c->next;
        }
        c->next=n;
        return c->next;
    }
};

Upvotes: 5

Views: 205

Answers (4)

Rob K
Rob K

Reputation: 8926

head->next is NULL (doesn't point to anything) at the time that statement is evaluated.

Upvotes: 0

Simon Richter
Simon Richter

Reputation: 29586

head->next is evaluated first. The compiler is at liberty to do so; see this question.

Upvotes: 2

Drew Dormann
Drew Dormann

Reputation: 63765

You are experiencing undefined behavior.

The problem is that you are expecting head->next to be evaluated at a particular time (right before calling the last append(). But that is not guaranteed.

Upvotes: 10

littleadv
littleadv

Reputation: 20272

When you're passing head->next - its before changing it with head->append. I'm afraid you're confusing the order of writing with the order of execution.

In this case you're changing the value and reading it in the same execution statement, that's undefined behavior.

Upvotes: 2

Related Questions