A few basic things about working in C

Topics related to the API, programming discussions & questions, coding tips, bugs, etc. should go here.
Post Reply
PlayerOne
Posts: 21
Joined: Mon Sep 29, 2008 8:45 pm
Location: UK

A few basic things about working in C

Post by PlayerOne »

Well, I've finally found something I am quite enthusiastic to get started on, instead of my original project which I just kept putting off, and it has raised a few basic questions:

How big is an int? Should I be trying to stick to chars as much as possible, given that it's an 8-bit processor? What, if any, difference does it make if I happen to want to use shorts or longs? Are shorts faster than longs?

Should I use fixed-point arithmetic, or is it okay to use floating point? (I notice avr-libc seeems happy with doubles for the math stuff, but is that really wise, or is it just for compatibility?) It seems to me that fixed-point would be the sensible way to go, but I don't know the AVR architecture.
User avatar
Flecko
Posts: 158
Joined: Mon Jan 05, 2009 11:50 pm

Re: A few basic things about working in C

Post by Flecko »

I think I can help you out, PlayerOne.

First off, chars and unsigned chars are 8bits. This is nice because it aligns nicely with the fact that the 644 is an 8bit microcontroller. This also means that using chars allows the uC to do all its math using one register for each variable. Ints are 16bits which means that everytime you do an operation on an int, 2 registers get used instead of one. Its a smidge more complicated than that, but trust me, use smaller variable types wherever you can.

As for floating point versus fixed point, absolutely use fixed point. Floating point math requires a lot more operations per variable than fixed point, and can greatly slow things down. A good rule of thumb is to try and make things as simple as possible for the uC in code. For instance, instead of dividing by 2, just use the logical shift operation: "i >> 2" The best thing you can do is always try to keep it simple.

But hey, thats what makes this fun, right?
Best of luck!
PlayerOne
Posts: 21
Joined: Mon Sep 29, 2008 8:45 pm
Location: UK

Re: A few basic things about working in C

Post by PlayerOne »

Thanks, that's kind of what I expected, but I am deeply ignorant of the AVR architecture, so wanted to make sure. And also I couldn't see anything which said whether the ints were 16-bit or 32-bit. I tend to be in the habit of declaring things as (32-bit) ints even if they are only ever going to be 0 or 1, because on a 32-bit processor that is the "native" word size, and sometimes it is more expensive to address and handle smaller data types. I'll stick with chars where I can for the uzebox, though, and maybe use 16-bit (8.8) fixed-point for the tricky mathematical bits.
Post Reply