I have less than 3 months experience coding, so I've started using LeetCode to just build hours working with code beyond what's assigned in school.
I was working on trying to build a circular queue (FIFO), and it won't compile. I received the following error and I'm stumped:
solution.cpp: In member function enQueue Line 58: Char 2: error: control reaches end of non-void function [-Werror=return-type] }
One thing: I am specifically instructed NOT to use the std::queue library, so while I know that would likely be much easier, it's not an option.
Full code of what I built follows:
class MyCircularQueue
{
private:
int* data = nullptr;
int size;
int capacity;
int front_p;
int rear_p;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
data = new int[k];
size = 0;
capacity = k;
front_p = 0;
rear_p = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value)
{
if (!isFull() && isEmpty())
{
for (int i = 0; i < capacity; i++)
{
if (data[i] == 0)
{
data[i] = value;
size++;
front_p = data[i];
rear_p = data[i];
return true;
}
}
}
else if (!isFull())
{
for (int i = 0; i < capacity; i++)
{
if (data[i] == 0)
{
data[i] = value;
size++;
front_p = data[i];
rear_p = rear_p++;
return true;
}
}
}
else
{
return false;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue()
{
if (isEmpty())
{
return false;
}
else
{
front_p = front_p++;
return true;
}
}
/** Get the front item from the queue. */
int Front()
{
return front_p;
}
/** Get the last item from the queue. */
int Rear()
{
return rear_p;
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
for (int i = 0; i < size; i++)
{
if (data[i] != 0)
{
return false;
}
else
return true;
}
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
if (size == capacity)
{
return true;
}
else
return false;
}
};
You're getting that error because the execution thru enQueue
does not always end with a return
statement. Logically this may never happen but the compiler does not know that, as it sees that if one of the for
loops terminates with i >= capacity
you won't encounter a return
statement.
The simple fix is to remove that last else
and so that the return false;
will always execute at the end of the function.
}
return false;
}