You are here:

C++/explanations about the code pls



please, i seen this queue implementation in a textbook and i am abit confused about a statement in the code:  "if(tail+1==head || (tail+1==SIZE && != head)".why add a 1 to the tail? could you explain with the aid of a circular queue diagram?  i do know itz a circular queue.

void enqueue(int num){
 /*the next statement is what i really dont understand*/
         if(tail+1==head || (tail+1==SIZE && != head){
         cout<<"queue is full!!!";
         /*check dat the queue is rotating*/
         if(tail == SIZE) tail = 0;
         queue[SIZE]= num;

/*the next statement is what i really dont understand*/
         if(tail+1==head || (tail+1==SIZE && != head){

This will not compile; it has a syntax error.

Perhaps it should have been

         if( ( tail+1==head ) || ( (tail+1==SIZE) && (0==head) ) ){

This is a circular queue implemented using an array of size SIZE.
head is the index of the first element, tail is the index of the last element.

if you want to add a new element to the queue, its position would be tail+1.

The if statement
a. checks if this position is the position of the first element; if so the queue is full. ( tail+1==head )
b. if the current position of tail is the last element of the array (tail+1==SIZE)
     i. the position of the new element would be 0 - circular, so go to the start of the array
     ii. if the beginning of the array is occupied by the first element the queue is full (0==head)

For a diagram see
the 'front' is your 'head', the 'rear' is your 'tail'  


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2017 All rights reserved.