Avatar

Please consider registering
Guest

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
Avatar
mkelvin
Member
Members
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:
4 Guest(s)

Currently Browsing this Page:
1 Guest(s)

Top Posters:

Skyler: 47

Peter: 41

Derek: 41

clau_ste: 39

Frodson: 38

Gwen: 32

EZB: 24

lppier: 23

Msaldaña: 18

Jorge: 17

Member Stats:

Guest Posters: 1

Members: 477

Moderators: 1

Admins: 4

Forum Stats:

Groups: 11

Forums: 30

Topics: 483

Posts: 1877

Newest Members:

Jaggxn, sam, annaharris, Marie Weaver, kev, Steven, Mr Anderson, mguy, omelc

Moderators: W Pirkle: 143

Administrators: Tom: 65, JD Young: 80, Will Pirkle: 0, W Pirkle: 143