0

I was wondering if you could use parentheses to group logical and/or "&& ||".

I am writing up the part where I check if the file block is a jpeg and having saved the 512 byte array. I check:

if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))

Am I allowed group the "or" like this with a paratheses? Does what I wrote mean that buffer 0-2 must be equal to their counterparts and buffer [3] can be either 0xe0 or 0xe1? Do I even need the parentheses at all, due to order of operation?

1 Answer 1

1

in C, the logical AND operator (&&) has higher precedence than the logical OR operator (||). see C Operator Precedence!

this means that && operators get evaluated before || operators. for example:

a && b || c

gets evaluated as

(a && b) || c

not

a && (b || c)

the two expressions are different. here are their truth tables

expression
(a && b) || c    

a    b    c    value
F    F    F    F
F    F    T    T
F    T    F    F
F    T    T    T
T    F    F    F
T    F    T    T
T    T    F    T
T    T    T    T

expression
a && (b || c)    

a    b    c    value
F    F    F    F
F    F    T    F
F    T    F    F
F    T    T    F
T    F    F    F
T    F    T    T
T    T    F    T
T    T    T    T

parentheses can be used to group sub-expressions typically to force different precedence. parenthesized sub-expressions are always evaluated before their containing expressions.

sometimes parentheses are used just to improve readability.

to answer your question, the expression

buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
    (buffer[3] == 0xe0 || buffer[3] == 0xe1)

is not the same as

buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff &&
    buffer[3] == 0xe0 || buffer[3] == 0xe1

see why?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .