Why '&&' and not '&'?

前端 未结 16 1565
别跟我提以往
别跟我提以往 2020-11-27 12:11

Why is && preferable to & and || preferable to |?

I asked someone who\'s been programming for years a

16条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 13:14

    Quickest (and slightly dumbed down) way to explain this to people who do not NEED to know the exact operations of the code when doing this is

    && is doing a check on each of those conditions Until it finds a false and returns the entire outcome as false

    || is doing a check on each of those conditions Until it finds a true and returns the entire outcome as true.

    & is doing MATHS based apon BOTH/ALL the conditions and dealing with the outcome.

    | is doing MATHS based apon BOTH/ALL the conditions and dealing with the outcome.

    I've never come across a point where I have needed to use & or | within an if statement. I mostly use it for cutting up Hexadecimal values into its component colours using bitwise shift.

    EG:

    r = fullvalue >> 0xFF & 0xFF;
    g = fullvalue >> 0xF & 0xFF;
    b = fullvalue & 0xFF;
    

    Within this operation "& 0xFF" is forcing to only look at of the binary value. I have not personally found a use for | yet though.

提交回复
热议问题