Reputation: 41
I am trying to code a FIFO queue which takes data in and once full releases the oldest piece of data to make room for the new data.
I am new at programming but have managed to come up with the following code:
int Q[size], f=0, r=-1;
int Qfull()
{
if (r==size) return 1;
return 0;
}
int Qinsert()
{
if(Qfull())
{
elem=Q[f];
f=f+1;
return elem;
r++;
Q[r]=SPI1BUF;
}
else
{
r++;
Q[r]=SPI1BUF;
}
}
The problem i am having is that this does not shift data and will fail once the array is full due to r increasing past the array size. Is there any way to solve this?
Upvotes: 4
Views: 6207
Reputation: 89
What Dan said, and you really can't put statements after a return
; they don't get executed.
Upvotes: 1
Reputation: 482
You are trying to make a cyclic queue without doing the extra steps to make that work. You either need to do that (as mentioned by cHao) or look into using a linked list. I would recommend working towards the cyclic queue as it should not require much modification.
Also, you have the same two lines in both of your if/else clauses. You should be able to move those two lines out and save yourself that if clause. I'm not 100% on your logic, so make sure that it can go before the if statement.
int Qinsert()
{
r++;
Q[r]=SPI1BUF;
if(Qfull())
{
//...
}
}
Upvotes: 0