Saturday, July 13, 2013

Differences between bitwise OR and Logical OR in C#


Difference between bitwise OR and Logical OR in C#

Laugh between | and ||

Most of time we use bitwise OR rather than logical OR. But there is a very small thing which can sleep our eyes. Recently I was using and surprised in one business logic which was going fail. Then I relies it's been serious to use it.


            int a1 = 0, b1 = 0;

            bool x = (a1 == 0 || ++b1 != 0);/* here b1 is still 0. the '++b1 != 0' was not evaluated */

            Console.Write(x);/* True*/
            Console.Write(a1);/* 0 */
            Console.Write(b1);/* 0 */

            int a2 = 0, b2 = 0;

            bool y = (a2 == 0 | ++b2 != 0);/* here b2 is 1. the '++b2 != 0' was evaluated. */

            Console.Write(y);/* True */
            Console.Write(a2);/* 0 */
            Console.Write(b2);/* 1 */

I hope it helps you somewhere.


No comments:

Post a Comment