I am very new to c programming and we are studying and/or truth tables. I get the general idea of how to do something like C & 5 would come out to 4, but I am very confused on the purpose of this? What is the end goal with truths and falses? What is the question you are seeking to answer when you evaluate such expressions? I'm sorry if this is dumb question but I feel like it is so stupid that no one has a clear answer for it
Asked
Active
Viewed 61 times
0
-
Related: https://stackoverflow.com/questions/276706/what-are-bitwise-operators – Passerby Feb 08 '22 at 23:17
-
1Can you please clarify? The title has `&&` but the question has `&`. They are different so need to be more precise. – kaylum Feb 08 '22 at 23:20
-
2Short answer: They are used for propositional logic. – eerorika Feb 08 '22 at 23:20
-
Please keep reading the tutorial – Mad Physicist Feb 08 '22 at 23:28
1 Answers
2
You need to understand the difference between &
and &&
, they are very different things.
`&` is a bitwise operation. 0b1111 & 0b1001 = 0b1001
ie perform a logical and on each bit in a value. You give the example
0x0C & 0x05 = 0b00001100 & 0b00000101 = 0b00000100 = 4
&&
is a way of combining logical tests, its close the the english word 'and'
if(a==4 && y ==9) xxx();
xxx
will only be executed it x is 4 and y is 9
What creates confusion is that logical values in C map to 0 (false) and not 0 (true). So for example try this
int a = 6;
int j = (a == 4);
you will see that j is 0 (because the condition a==4 is false.
So you will see things like this
if(a & 0x01) yyy();
this performs the & operation and looks to see if the result is zero or not. So yyy will be executed if the last bit is one, ie if its odd

pm100
- 48,078
- 23
- 82
- 145