-2

The code is not throwing any error but it is not taking the values that we pass in the enqueue function. Here is the code:

#include <bits/stdc++.h>
#include <climits>
using namespace std;

struct Queue{
    int *arr;
    int front , rear;
    int cap;
    Queue(int c){
        cap = c;
        front = -1;
        rear = -1;
        arr = new int[cap];
    }
    void enqueue(int x){
        if(rear == cap-1){
            cout<<"The array is full";
        }
        rear++;
        arr[rear] == x;
        cout<<arr[rear]<<endl;
    
        if(front == -1){
            front = 0;
        }
    }
    int dequeue(){
        int data;

        if(front == -1){`your text`
            cout<<"Array is empty";
            return INT_MIN;
        }
    

        data = arr[front];
        arr[front] = 0;
    
        if(front == rear){
            front = rear = -1;
        }
        else{
            front++;
        }
        return data;
    }
};
int main() {
    Queue q(3);

    q.enqueue(24);
    q.enqueue(30);
    q.enqueue(42);

    cout<<q.dequeue();
    return 0;
}

the enqueue function is taking some garbage value instead of the integer value that we are passing in the argument.

MAK136
  • 1

1 Answers1

1

Hi and welcome to Stackoverflow.

The problem is that you ignored your compiler warnings. Under https://godbolt.org/z/Pn1Mf115T i have thrown your code in an online compiler and it tells me/you:

<source>:20:19: warning: equality comparison result unused [-Wunused-comparison]
        arr[rear] == x;
        ~~~~~~~~~~^~~~
<source>:20:19: note: use '=' to turn this equality comparison into an assignment
        arr[rear] == x;
                  ^~
                  =
1 warning generated.
Compiler returned: 0

So the compiler tells you that you comparing instead of assigning the values. Thats the reason why your queue takes garbage values, it just never gets data assigned and the output is the uninitialized memory from your C-style array.

Rule of thumb: Do not ignore compiler warnings.

Zaiborg
  • 2,492
  • 19
  • 28