+ 11

Strange C Program

I found out this code recently. It works exactly how it's supposed to. But, it's a very strange way to do it (line 3). Could someone explain why/how this code works? int n; scanf("%d", &n); (n & 1 && printf("odd")) || printf("even");

2nd Sep 2018, 4:00 AM
Lucas Jadilo
Lucas Jadilo - avatar
3 Antworten
+ 8
& - unary 'and' (performs 'and' operation on a binary level) && - logical and (0 is false, everything else is true), Logical and evaluates from left to right, so if the first condition is false (eg 0 && 1), it wont check the second one eg: 0 && (1+383+388393639) here as the first condition is false, second one is ignored || - logical or (inverse of &&) unary & rules: 1 1 = 1 1 0 = 0 0 1 = 0 0 0 = 0 let n = 7 let n = 6 binary of 7 = 111 bin of 6 = 110 binary of 1 = 001 bin of 1 = 001 So 7&1 is So 6&1 is 1 1 1 1 1 0 0 0 1 0 0 1 ------- --------- 0 0 1 0 0 0 1 so true 0 so false first condition is first condition is true, false, so second so second condition is condition is also checked. ignored. (prints odd) Third condition Third condition is ignored is checked
2nd Sep 2018, 5:15 AM
‎ ‏‏‎Anonymous Guy
+ 5
Lucas Jadilo n&1 is bitwise and operation.. if bitwise and is performed for 1 with even number, value is always zero...if bitwise and is performed for 1 with odd number, value is always one...You can verify this in playground if you wish... now , we have evaluated n &1 which is 1 for odd numbers and 0 for even numbers... in case of even numbers, it becomes 0 && print("odd").. for && operators , if one condtion is failed, Second is not at all evaluated as output of combined condition is failed only...so, printf("even") gets executed to print even as output... in case of odd, printf(" odd") gets evaluated and it prints odd...
2nd Sep 2018, 5:21 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 3
A hint for anyone who wants to take a stab at this: n & 1 is a bitmask
2nd Sep 2018, 5:10 AM
Kirk Schafer
Kirk Schafer - avatar