2

I just created an implementation of LinkedList(just for self-education purpose.). I made it run, but the output result is kind of weird... Here is the code:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>

using namespace std;

template <class T>
class Node{
T datum;
Node<T> *_next;
public:
 Node(T datum)
{
    this->datum = datum;
    _next = NULL;
}
 void setNext(Node* next)
 {
     _next = next;
 }
 Node* getNext()
 {
     return _next;
 }
 T getDatum()
 {
     return datum;
 }          
};

template <class T>

class LinkedList{
Node<T> *node;
Node<T> *currPtr;
Node<T> *next_pointer;
int size;
public:
LinkedList(T datum)
  {
      node = new Node<T>(datum);
      currPtr = node;  //assignment between two pointers.
      next_pointer = node;
      size = 1;
  }
LinkedList* add(T datum)  // return pointer type.
{
   Node<T> *temp = new Node<T>(datum);
   currPtr->setNext(temp);
   currPtr = temp;
   size++;
   cout<<datum<<" is added.";
   return this; //pointer type specification
}
T next()
{
   T data = (*next_pointer).getDatum();
   cout<<data<<" is visited.";
   next_pointer = next_pointer->getNext();
   return data;
}
int getSize()
{
   return size;
}   
};

Now I tried to use LinkedList:

int main()
{
LinkedList<int> *list = new LinkedList<int>(1);
list->add(2)->add(3)->add(4);
cout<<endl;

printf("%d %d %d %d",list->next(),list->next(),list->next(),list->next());  \\One

cout<<list->next()<<"\n"<<list->next()<<"\n"<<list->next()<<"\n"<<list->next()<<endl; \\Two

cout<<list->next()<<endl;\\Three
cout<<list->next()<<endl;
cout<<list->next()<<endl;
cout<<list->next()<<endl;
}

The output One will display the data : 4 3 2 1. Two will display 4 3 2 1. Three will display 1 2 3 4. I don't know what happened during the runtime. All of them should output the data in 1 2 3 4 sequence... I'd appreciate your help! Thanks!

1 Answer 1

10

The order in which parameters are evaluated is unspecified, so:

printf("%d %d %d %d",list->next(),list->next(),list->next(),list->next());

could evaluate the last list->next() first, or the middle one...

EDIT: Just tackling what I assume is the issue, as I doubt that's the actual code: http://ideone.com/avEv7

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a fixed evaluation order for C++? Or you can specify it by yourself? Thanks!
@Gao no (at least for C++03). Get the values before the printf and store them in variables.
@Gao: Evaluation order in C++ is unspecified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.