17

I see a lot of templates and complicated data structures for implementing a circular buffer.

How do I code a simple integer circular buffer for 5 numbers?

I'm thinking in C is the most straightforward?

Thanks.

4
  • 7
    The complexity of the code goes up with how safe and robust you want it to be. Do you want it to prevent underflow/overflow, for instance? Commented Sep 1, 2010 at 20:38
  • 3
    Note: a circular (ring) buffer is different than a circular queue. Commented Sep 1, 2010 at 20:42
  • I just need to store the 5 last values of some data, so whatever has a better design to do that. Commented Sep 1, 2010 at 20:43
  • 1
    @T.T.T. Do you need to retrieve them in a special order (FIFO, LIFO, no ordering) ? Commented Apr 3, 2015 at 15:11

4 Answers 4

29

Have an array, buffer, of 5 integers. Have an index ind to the next element. When you add, do

buffer[ind] = value;
ind = (ind + 1) % 5;
Sign up to request clarification or add additional context in comments.

2 Comments

From the personal experience file, you need to be careful that ind is not negative. If you change the second line to "ind = (max(0,ind) % 1) + 5;", you don't have to worry about negative values for ind.
Why don't you just set ind to be uint? That would solve your problem more efficiently if only additions are involved
12

Take an array, arr, an index idx, and a counter, num.

To insert foo, say arr[idx++] = foo; idx %= buffer_len; num++;.

To read out an item into foo, say foo = arr[(idx-num)%buffer_len]; num--;.

Add boundary checks.

1 Comment

You don't need num and idx.
1

If the size and data type of your buffer are fixed, a simple array is all you need:

 int buffer[5];

Add to that a couple pointers:

 int* start = &buffer[0];
 int* end   = &buffer[4]+1;
 int* input = start;
 int* output = start;

Comments

-1
int rI =0;
int wI=0;
#define FIFO_SIZE 3
int checkAvail()
{
int avail=0;

if(wI<rI)
    avail= (rI-wI);
else
    avail = (FIFO_SIZE-wI+rI);
return avail;
}

int addFIFO(int *a, int val)
{
if(checkAvail()>0)
{
    a[wI]=val;
    wI++;
    if(wI>FIFO_SIZE)
        wI=0;
}
else
{
    printf("FIFO full");
}
return 0;
}
 int remFIFO(int *a)
 {
 int val;
if((FIFO_SIZE-checkAvail()>0))
{
    val =a[rI];
    rI++;
    if(rI>FIFO_SIZE)
        rI=0;
}
else
{
    printf("FIFO empty");
}
return 0;
}
int main(array<System::String ^> ^args)
{
int FIFO_ARRAY[FIFO_SIZE]={};
addFIFO(FIFO_ARRAY,1);
addFIFO(FIFO_ARRAY,2);
addFIFO(FIFO_ARRAY,3);
addFIFO(FIFO_ARRAY,4);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
remFIFO(FIFO_ARRAY);
}

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.