Click here to Skip to main content
15,908,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a very simple queue class
Header file: Queue.h

C++
#ifndef QUEUE_H
#define QUEUE_H
struct Node
{
	int data;
	Node* link;
};
typedef Node* nodeptr;
class Queue
{
public:
	Queue();
	~Queue();
	void add(int number);
	int remove();//removes the top node of the queue and return its value
	bool empty() const;
protected:
	nodeptr front;
	nodeptr back;
};
#endif //QUEUE_H 


Implementation file: Queue.cpp

C++
#include "Queue.h"
#include <cstdlib>
#include <iostream>
#include <cstddef>
using namespace std;
Queue::Queue():front(NULL),back(NULL)
{}
Queue::~Queue()
{
	int next;
	nodeptr discard;
	discard=front;
	while (discard!=NULL)
	{
		next=remove();
		discard=front;
	}
}
void Queue::add(int number)
{
	if (empty())
	{
		front=new Node;
		front->data=number;
		front->link=NULL;
		back=front;
	}
	else
	{
		nodeptr temp;
		temp=new Node;
		temp->data=number;
		temp->link=NULL;
		back->link=temp;
		back=temp;
	}
}
int Queue::remove()
{
	if (empty())
	{
		cout<<"error removing from an empty queue\n";
		exit(1);
	}
	else
	{
		int result=front->data;
		nodeptr discard;
		discard=front;
		front=front->link;
		if (front==NULL)
		{
			back=NULL;
		}
		delete discard;
		return result;
	}
}
bool Queue::empty() const
{
	return (front==NULL);
}


I have two versions of main program which are basically the same but produce different results despite the fact that the class is untouched.
Main version 1- output: 4321

C++
#include "Queue.h"
#include<iostream>
using namespace std;

int main()
{
	Queue a;
	a.add(1);
	a.add(2);
	a.add(3);
	a.add(4);
	cout<<a.remove()<<a.remove()<<a.remove()<<a.remove();
}


Main version 2-output:
1
2
3
4

C++
#include "Queue.h"
#include<iostream>
using namespace std;
int main()
{
	Queue a;
	a.add(1);
	a.add(2);
	a.add(3);
	a.add(4);
	cout<<a.remove()<<endl;
	cout<<a.remove()<<endl;
	cout<<a.remove()<<endl;
	cout<<a.remove()<<endl;
}



What I have tried:

I have change between either versions hundreds of times but the results are unchanged. What did I do wrong here?
Posted
Updated 14-Aug-16 9:26am
v2

1 solution

A C language compiler is a rewriter. This means that the compiler decide the order of evaluation of the parts in a single line of source code.
C++
cout<<a.remove()<<a.remove()<<a.remove()<<a.remove();
The compiler find it is more efficient to evaluate in reverse order;
You can check with this:
C++
cout<<a.remove()+10<<a.remove()+20<<a.remove()+30<<a.remove()+40;
 
Share this answer
 
Comments
ducdohuunguyen 14-Aug-16 23:30pm    
Do you know any way to prevent such behavior?
Patrice T 14-Aug-16 23:46pm    
Use your version 2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900