Specific usage of if loop

Feb 4, 2015 at 12:44pm
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 Feb 4, 2015 at 1:00pm
Feb 4, 2015 at 12:50pm
Last edited on Feb 4, 2015 at 12:54pm
Feb 4, 2015 at 12:57pm
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)
?
Feb 4, 2015 at 1:03pm
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.
Feb 4, 2015 at 2:25pm
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. 
Feb 4, 2015 at 2:29pm
if (m % 2) is identical to if (m % 2 != 0).
Damn. I do not know what I been thinking. Thanks.
Feb 4, 2015 at 4:45pm
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.

Feb 5, 2015 at 8:28pm
Thank you people :)
Feb 6, 2015 at 11:59am
Also, if is not a loop...
Topic archived. No new replies allowed.