Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
};
like image 621
user1128516 Avatar asked Jan 03 '12 19:01

user1128516


2 Answers

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.

like image 111
Drew Dormann Avatar answered Oct 14 '22 11:10

Drew Dormann


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.

like image 22
littleadv Avatar answered Oct 14 '22 12:10

littleadv