Can you explained this??

+1 ♦Avishka RJ ♦™ · March 14, 2015
/images/forum/upload/2015-03-14/9a2ebd0d32016bd714014da4db48eff5.pngI  typed this code mistakenly but this compiled and gave a answer. Can you explain how "&&"  react in here??

Post a Reply


Oldest  Newest  Rating
+1 ♦Avishka RJ ♦™ · March 14, 2015

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
    for(int a=0;a<25;a++){

+1 Dol Lod · March 14, 2015
When you do &&, it evaluates to either true or false depending on whether the condition is met. For example, 5&&5 is true while 5 &&6 is false. The boolean value of true or false is then cast to an int implicitly meaning 0 if it is false and 1 if it is true. Therefore 1 is added to 1 most of the time printing out 2 since the majority of the time, rand() will not give out 6. 
+1 ♦Avishka RJ ♦™ · March 14, 2015
Then How about this?? In here there's only one "&" symbol.

+1 Dol Lod · March 15, 2015
@Krootushas Gesu

Yeah, you're right. That's why I get for answering a question when sleep deprived.. 

To expand more on the bitwise and, you have to consider numbers in binary notation. Binary means everything is either a 0 or a 1. Essentially this means you are using base 2 representation it it makes more clear. The normal decimal system we use is base 10. Ex. is 100 for base 10 notation. 100 is 10^(3-1).

Now for binary notation: Each number means you take 2 to that power or not. I will be showing 8 bits only for simplicity when converting numbers.


The place of each bit starts from the right meaning the the rightmost spot is 2^0. One to the left of that is 2^(1), then 2^(2). If there is a 0 on that spot it means that bit is unused.

Now for & wise bit operations.

2&3 is 2 which is greater than 1 which is true because they have one bit in common that's a 1.  
2&4 is 0 which evaluates to false because they have no bits in common that are a 1. 

On the computer system, all numbers are stored in binary notation with 32 bits. Therefore, when you perform an & operation, you & all the bits together.

ex. 0 & 0=0 0 &1=0 1&1=1

So when you do &, you really & all 32 bits together.

So if you do something like 2&3,you will get 1 b/c they have the 1 bit in common, the one representing the two's place. 
+1 ♦Avishka RJ ♦™ · March 15, 2015
Can you explain this more?? :blink:
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator