[sdiy] Quick C query

Tom Wiltshire tom at electricdruid.net
Sun Nov 21 17:57:20 CET 2010


>> What's the best way to deal with booleans in C?
> What is it that you are trying to do?  Do you have individual boolean values that you are looking for efficient storage?  Do you have complicated expressions that you want to simplify?

I have individual booleans and I'm looking for efficient storage. Using a whole byte for each one makes me go "ugh!". But if it makes doing conditional tests on those booleans horrible, I'm willing to swallow the frog and use a byte per boolean.

> Some example code would help.

Well, in assembly, I'd have something like this:

	MainFlags:		.space 2		; 2 bytes, enough for 16 flags

	.equiv	EDIT_MODE, 0
	.equiv	RELEASE_DELAY, 1
	etc etc

Then I can do things like;
	btfss	MainFlags, #EDIT_MODE		;  Test the flag, skip if set
	goto	NotEditMode					; Flag not set - jump off elsewhere
	.EditMode							; Flag set code follows

I've copied this fairly directly into C like this (howl if this is a really bad idea...):

	struct MainFlags {
		unsigned	EditMode :1
		unsigned	ReleaseDelay :1
		unsigned	ButtonPressed:1

	} MainFlags;

	// I can then set these up
	MainFlags.EditMode = 0;
	MainFlags.ReleaseDelay = 0;
	MainFlags.ButtonPressed = 0;

My reason for doing this was that it's how Microchip have chosen to expose many bitfield settings in various dsPIC registers, so it follows their example. Whether it's right in my case, I don't know.

For instance, setting up the Clock pre-division:


Their header files define CLKDIVbits and the individual bits within it. I just copied their structure.

> Thing is with C, there are so many ways to do things it all really depends on the specific application.

That's usually the way it goes. However, what makes programming interesting is that if you ask n programmers which is the best way for a specific application, you can be guaranteed to get at least n different answers!

>> If it makes any odds, I'm using Microchip's C Lite on dsPIC.
> Does that have any target-specific or vendor-specific extensions?

I have no idea currently. I don't even know what size short or long ints I've got, although I could have a good guess. These are early days.

> Once you see the light you'll wonder why you never jumped before!!!

I sincerely hope so! It'd be nice to work in something that produced results quicker than assembly. I doubt I'll ever leave "hand-tweaked" behind for audio-rate stuff though.


More information about the Synth-diy mailing list