Specific usage of if loop

Hey guys. I'm practicing programming from this book I have, and one of the solutions contains this unusual usage of if loop:

(simplified code)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main()
{
    char m;
    //(...)
    std::cin >> m;
    if(m & 1){
        //(...)
        std::cout << "(m & 1) is true\n";
    }

    return 0;
}


Is there any reason why "m & 1" condition would be used instread of just
if(m)
or
if(m != 0)
?
Last edited on
Last edited on
That cleared it up, thank you =)

But anyway, is there any reason why would anyone use this kind of approach instead of something more easily readable, like:
if(m % 2)
?
It is still not eqivalent. Correct one: if(m % 2 != 0)
Now about the reason:
1) It is might be there to demonstrate something. Look further in the book if it explains choice of that approach
2) On old compiler it might be actually faster. (modern compilers will optimize it and give you same assembly for both variants). So if book is old, then that might be the case.
3) No reason.
if (m % 2) is identical to if (m % 2 != 0).

As for the reason, you might use m&1 if m is used as a bit field. If it is really a number and you want to see if it's odd, then m%2 would be appropriate. The difference is in readability of the code:
1
2
3
4
5
6
if (test1) m |= 1;
if (test2) m |= 2;
if (test3) m |= 4;
...
if (m%2)... // huh? m is a bunch of bits, why are you looking at the value?
if (m&1)... // clearly you're looking to see if test1 succeeded. 
if (m % 2) is identical to if (m % 2 != 0).
Damn. I do not know what I been thinking. Thanks.
Don't confuse "&&" with "&"

4 & 2 == 2 , while 4 && 2 == true

technically, "if (m & 1)" and "if (m % 2)" are more explicitly written as "if ((m & 1) != 0)" and "if ((m %2) != 0)"

The first form is producing a char, and the second one a bool. The two forms are equivalent when tested with "if" because if operates on bool and the result is implicitly converted to bool, and non-zero values evaluate to true when converted to bool.

Thank you people :)
Also, if is not a loop...
Topic archived. No new replies allowed.