Question

The following snippet of C code (where a and b are both type double) is what my question is about:

if(1.0-a < b && b <= 1.0)

Based on the order of operations shown in Wikipedia I understand this as evaluating the same as the following code snippet with parentheses:

if( ( (1.0-a) < b ) && ( b <= 1.0) )

which is what I want. I just want to double check my understanding that the two code snippets are indeed equivalent by the order of operations in C.

Note: obviously I could just use the second code snippet and make explicit what I want if() to evaluate; I ask because I've used the first snippet in my code for a while and I want to make sure my previous results from the code are okay.

Was it helpful?

Solution

Quick answer: yes, it is equivalent.

This means that the result of both code snippets is the same; the meaning is the same, but be careful when you talk about order of operations. It looks to me like your question here is about precedence and associativity. The latter tells you what an expression means, not the order of evaluation of its operands. To learn about order of evaluation, read about sequence points: Undefined behavior and sequence points

OTHER TIPS

You ask about "order of operations", but I don't think that's what you really want to know.

The phrase "order of operations" refers to the time order in which operations are performed. In most cases, the order in which operations are performed within an expression is unspecified. The && operator is one of the few exceptions to this; it guarantees that its left operand is evaluated before its right operand (and the right operand might not be evaluated at all).

The parentheses you added can affect which operands are associated with which operators -- and yes, the two expressions

1.0-a < b && b <= 1.0

and

( (1.0-a) < b ) && ( b <= 1.0)

are equivalent.

Parentheses can be used to override operator precedence. They do not generally affect the order in which the operators are evaluated.

An example: this:

x + y * z

is equivalent to this:

x + (y * z)

because multiplication has a higher precedence than addition. But the three operands x, y, and z may be evaluated in any of the 6 possible orders:

x, y, z
x, z, y
y, x, z
y, z, x
z, x, y
z, y, x

The order makes no difference in this case (unless some of them are volatile), but it can matter if they're subexpressions with side effects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top