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

T.T.T. picture T.T.T. · Sep 1, 2010 · Viewed 42.3k times · Source

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.

Answer

Matthew Flaschen picture Matthew Flaschen · Sep 1, 2010

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;