Sunday, April 22, 2007

 
Well Forrest, here's me being stupid..

Anybody notice a systemic logic problem here?

void toggleP12v()
{
if(P12v == 0)
{
P12v = 1;
}
else
{
P12v = 1;
}
}
void toggleP5v()
{
if(P5v == 0)
{
P5v = 1;
}
else
{
P5v = 1;
}
}
void toggleClock()
{
if(Clock == 0)
{
Clock = 1;
}
else
{
Clock = 1;
}
}

Cut and paste can get you! Lol they turn on just fine by the way.

Comments:
void toggleP12v()
{
P12v ^= 1;
}

Less scope for error ;-)
 
hmm.. did you mean P12v ^= P12v?
I found that I had to represent 2*a as a+a or I got a mulchar error in sdcc, so I went for simple assignments :) Did you oops now too? Maybe its communicable.
 
Bart, I certainly do make lots of typos so I try to make my code as short as possible. However that was not one of them.

In C ^= means exclusive or and assign so x ^= 1 is short for x = x ^ 1 which just toggles the bottom bit of x.

What is P12v defined as? If it is a macro it may need to parenthesis it. Or perhaps your compiler is broken. To prove to myself I was not going mad I tested it with the Comeau compiler try it out page at http://www.comeaucomputing.com/tryitout .
This is the ultimate arbitor for solving programmer versus the compiler disputes. I defined P12v as a bit field for the test.

struct x {
int y : 1;
} z;

#define P12v z.y

void toggleP12v()
{
P12v ^= 1;
}
 
Thanks for the tip, I didn't recognize the usage. Assuming it works in SDCC, it would have done the trick. I like to code with simple constructs that anyone can understand. As you can see, I need to keep it simple :)
 
i'm not sure if this version works in C, but i use this in PHP all the time:

flag = !flag;
 
Zach,
Yes it does work in C but its meaning is slightly different. My example toggles the bottom bit, regardless of the size of the variable. ! will read all the bits and if not zero set the result to 0 else 1. If P12v is a single bit variable then the effect is identical. Depending on the compiler and the instructions set one may be more efficient than the other.
 
Post a Comment

Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to
Posts [Atom]