How do I code a simple integer circular buffer in C/C++?

42,695

Solution 1

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;

Solution 2

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.

Solution 3

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;
Share:
42,695
T.T.T.
Author by

T.T.T.

Updated on July 09, 2022

Comments

  • T.T.T.
    T.T.T. almost 2 years

    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.

  • photo_tom
    photo_tom over 13 years
    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.
  • user3467349
    user3467349 about 9 years
    You don't need num and idx.
  • Triskeldeian
    Triskeldeian about 8 years
    Why don't you just set ind to be uint? That would solve your problem more efficiently if only additions are involved