Hi,
Could anyone please explain to me the following:
Is there a condition here? What actually forms the condition? Is it the '!'? Why does it return 0 with probability 2/3 (i.e. how does it work)?Code:int a = !(rand () % 3);
Hi,
Could anyone please explain to me the following:
Is there a condition here? What actually forms the condition? Is it the '!'? Why does it return 0 with probability 2/3 (i.e. how does it work)?Code:int a = !(rand () % 3);
Can it be interpreted thus - if number is not divisible by 3 a=0, else a=1?
In C, any non-zero value is regarded as 'true', so when you have an expression such as
if ( x )
there is an implicit
if ( (x) != 0 )
going on.
So the implied inner condition is
int a = !((rand () % 3) != 0);
You can then cancel out the negations, and arrive at
int a = (rand () % 3 == 0 );
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.