View previous topic :: View next topic |
Author |
Message |
Guest
|
Problem with structs and operators |
Posted: Sat Jul 19, 2008 7:50 am |
|
|
Hi
I cant understand why (2 is not working. As I understand a int is true when >0 and only false when =0
sw.x is a struct and defined as int.
(1
Code: | //working
if ((sw1.counter>0) & (sw2.counter>0)){
do...;
} |
(2
Code: | //not_working
if ((sw1.counter) & (sw2.counter)){
do...;
} |
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sat Jul 19, 2008 12:22 pm |
|
|
Please read about the difference between bitwise and logical operators.
Also read about the result of logical expressions.
See pages 9 and 10 in this reference:
http://cslibrary.stanford.edu/101/EssentialC.pdf |
|
|
Guest
|
|
Posted: Sat Jul 19, 2008 2:05 pm |
|
|
Thanks for reply.
I a little confused because if:
int a=0
int b=1
(a & b) will be processed complete and result is = 0
(a && b) will only exam "a" because "a" = 0, and then the case will be = 0
but maybe I wrong, according the pdf you send me will
it work if I use (&&) but it dosent work, I just tested it.
Maybe you can explain a little? |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1909
|
|
Posted: Sat Jul 19, 2008 3:00 pm |
|
|
The bitwise AND: &. It performs a bitwise AND; for example 0x27 & 0x13 = 0x03.
The logical AND: &&. It performs a logical AND: for example logging && !armed is only true if logging = TRUE AND !armed = TRUE (in other words, armed = FALSE).
What PCM was getting at when he recommended that you look up the result of logical expressions was that the compiler is doing what you're asking it to; you just don't know how to ask it to do what you want.
In your original post you had this line: "if ((sw1.counter > 0) & (sw2.counter > 0))". sw1.counter is first tested to determine if it is > 0. The result is either 1 (it is greater than 0) or 0 (it's not). sw2.counter is then tested to determine if it is > 0. The result of this comparison is either 1 or 0 as well. Then these results are bitwise ANDed and if the result is 1, the if () statement is executed. The if statement will execute only if both counters are > 0. You kind of stumbled into this (what you want) even though your coding isn't exactly what is standard. Instead of &, you should have used the logical and, &&.
Your example 2, however doesn't do what you want: "if ((sw1.counter) & (sw2.counter))". For argument's sake, let's say that sw1.counter = 0xa5 and sw2.counter = 0x32. 0xa5 & 0x32 = 0x20. In effect, your code is asking "is 0x20 equal to TRUE (1)?"
Clearer? |
|
|
Guest
|
|
Posted: Mon Jul 21, 2008 9:57 am |
|
|
Sorry for the late reply.
I'm pleased for the pdf, and the great examples.
My application I now running as design!
Many thanks:-) |
|
|
|