Go Down

### Topic: Is this a bug or am I missing something? (Read 962 times)previous topic - next topic

#### CowboyBob

##### Apr 03, 2010, 06:19 pm
This never evaluates to true and the code inside the if statement does not get executed.  However when I serial.print the values in the if statement, the values are AP==-3, AC==30 and val == 35.  The only thing I can see that might be an issue is that AP is signed and a negative value where the other values are unsigned.  Is it not possible to compare signed and unsigend integers?

unsigned int val = 35;
unsigned int AC = 30;
int AP = -3;

if (val==35 && AP < AC){
//do something
}

#### hakoni

#1
##### Apr 03, 2010, 10:38 pmLast Edit: Apr 04, 2010, 01:23 am by hakoni Reason: 1
See:

http://c-faq.com/expr/preservingrules.html

In short "To avoid surprises (under either set of rules, or due to an unexpected change of rules), it's best to avoid mixing signed and unsigned types in the same expression"

PS: Edit: g++ with -Wall args warns about this. I would like to have such warnings present in Arduino Uno Punto Zero

#### brtech

#2
##### Apr 05, 2010, 03:45 pm
Yeah, I think you are getting unsigned arithmetic.

Try saying
if (val==35 && AP < (int)AC){

#### raron

#3
##### Apr 06, 2010, 03:08 pm
Or try

unsigned int val = 35;
unsigned int AC = 30;
int AP = -3;

if (val==35 && AP [glow]>[/glow] AC){
//do something
}
for the sake of testing, not that it is too useful
(As in, what is -3 binary,and what is this binary if it was unsigned?)

brtech's way is better of course, as long as the unsigned int's value is below 32768.

I got a little curious and skimmed through the atmega 328 assembler instructions. I find a lot of branch-if instructions, but no BRHI (or similar; branch if higher, unsigned). Only BRHS (branch if same or higher, unsigned I presume), and a lot of other signed and unsigned variations. Seems strange as one would have to combine at least two different tests for such a simple test, when the atmega have so many instructions. Unless I misunderstand and some of the other branch instructions are equivalent of a BRHI.

So, any assembler people here that know how an unsigned "branch if higher than" test is performed on atmega 328 at that level? Just curious, not that I will dabble in atmega assembler for a good while yet.

Go Up

Please enter a valid email to subscribe