Home > OS >  What is true and false and & | used for?
What is true and false and & | used for?

Time:02-10

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

CodePudding user response:

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

  •  Tags:  
  • c
  • Related