4

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?

4
  • 2
    cs.bu.edu/teaching/c/queue/array/types.html Commented Nov 4, 2013 at 16:04
  • Since you are learning so a direct code may not be the best answer for you. I suggest you look at the link above and/or ask more direct question on specific problems with your code :) Your QFull size check is wrong and therefore it will crash as soon as it fills up. Commented Nov 4, 2013 at 16:08
  • 1
    If your queue is of a fixed size, you might want to consider using a ring buffer. Have two pointers, one to the first element, and one to where the next should go. When you remove an element, just increment the "last element" pointer; if it's then equal to Q+size, set it to Q. Commented Nov 4, 2013 at 16:10
  • 1
    (You could do it with array indexes too, and that could be easier. Then you could just say next = (next + 1) % size;.) Commented Nov 4, 2013 at 16:13

2 Answers 2

1

What Dan said, and you really can't put statements after a return; they don't get executed.

Sign up to request clarification or add additional context in comments.

Comments

0

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())
    {
    //...
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.