Please consider registering

sp_LogInOut Log In sp_Registration Register

Register | Lost password?
Advanced Search

— Forum Scope —

— Match —

— Forum Options —

Minimum search word length is 3 characters - maximum search word length is 84 characters

sp_Feed sp_TopicIcon
Mod operator (or remainder operator) are great for circular buffers
No permission to create posts
February 23, 2014
10:26 am
Forum Posts: 14
Member Since:
February 22, 2014
sp_UserOfflineSmall Offline

Will, not sure why you seem not to prefer to use them in your code examples. They aren't as fast as a conditional check because mod operators are really remainder operators and perform a division each increment. Also, maybe you don't use them to avoid confusion?

However, in any case, I found this bit of code (in your oscillators chapter, pg 307), to be needlessly obfuscating:

int nReadIndexNext = (nReadIndex + 1) > 1023 ? 0 : nReadIndex + 1;

A more clear way to do this would be:
int nReadIndexNext = (nReadIndex + 1) % 1024;

mod operators have some downsides of course (i.e. division is more expensive than an if-statement) and they can fail if you expect them to work on negative numbers.

Since the buffer here is a power of 2, we can do the same mod-operator line with:

int nReadIndexNext = (nReadIndex + 1) & 1023; // or maxbuffersize - 1

This guy has no performance issues and is just as clear if you're used to bit operations.

Forum Timezone: America/New_York

Most Users Ever Online: 36

Currently Online:
7 Guest(s)

Currently Browsing this Page:
1 Guest(s)

Top Posters:

Skyler: 48

Derek: 46

Peter: 41

Frodson: 40

clau_ste: 39

Gwen: 32

JimmyM: 30

TheSmile: 27

EZB: 24

lppier: 23

Member Stats:

Guest Posters: 1

Members: 522

Moderators: 1

Admins: 4

Forum Stats:

Groups: 11

Forums: 31

Topics: 545

Posts: 2134

Newest Members:

Bill, hill william, NAUN_SONAR, sufy, Diane, Richard, drvenkman, venkman, Jfx, drorh

Moderators: W Pirkle: 247

Administrators: Tom: 67, JD Young: 80, Will Pirkle: 0, W Pirkle: 247