View Single Post
  #15   Spotlight this post!  
Unread 15-02-2006, 21:16
aaeamdar's Avatar
aaeamdar aaeamdar is offline
Post-A-Holic
AKA: Paul Dennis
FRC #1719 (The Umbrella Corp)
Team Role: College Student
 
Join Date: Jan 2006
Rookie Year: 2005
Location: Baltimore, MD
Posts: 231
aaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant futureaaeamdar has a brilliant future
Re: A few simple programming questions;

Quote:
Originally Posted by Keith Watson
I've seen bugs introduced when people use pre or post ++ at the wrong time.
An example? I'm curious.

Quote:
Originally Posted by Keith Watson
Even something as simple as always using parentheses to establish precendence instead of relying on operator precendence makes code much more understandable.
Some people think that there is somehow an advantage to cramming something into the fewest lines possible (ahem!). Sometimes it's necessary to optimize things even if these optimizations make things less readable. If your program does billions of mod 32 calculations, and you have some method

Code:
 
int mod32(int x)
{
     while (x > 32)
     {
            x -= 32;
     }

     return x;
}
This works and everyone should be able to tell what it does. I think there's also a modulus method in the C libraries, but I could be wrong. Anyway, the point is that this would probably be a fairly clear way of doing it. But if you were trying to reduce the amount of time your program takes (and it could take a while if you enter in large numbers and do millions of calculations) this is what you would want the method to do:

Code:
int mod32(x)
{
     return x & 31;
}
It's less understandable. Some people may not even know what the & operator does. An italisized description follows:

The & is a bitwise AND operation. In other words, it works with the ones and the zeroes. AND evaluates to true or one if cond1 and cond2 evaluate to one. Example: 7&11

7 = 4+2+1;
11 = 8+2+1;

0111
1011
____
0011


The bitwise operation works faster. It only works with powers of two (don't try x&10) but in those cases, it works. If you want, think about why (or PM me). Just draw it out.

However, oftentimes the best code for processing time is the most understandable too. Also, when you think about the speed of today's processors, unless you are writing code that /needs/ to run fast, there is not much point in optimizing.

[\END LECTURE]

That was rather off-topic, but I found it interesting. I hope you did too (or skipped over it).

Tat's all for now, folks. Tit for tat.
Paul Dennis