## Operators Precedence Query

6 posts / 0 new
Author
Message

Hi

I read a few manuals & I am still a little bit stump.
I have this piece of code from someone else very old program & they are not around any more.

```int Voltage, Offset;
Voltage += Offset * 4 * 6;```

From what I can work out that you work from left to right.

So if I break this down, it should be equivalent to in basic term.

My interpretation is this one

`Voltage = (Voltage + Offset) * 4 * 6`

Not this

`Voltage = Voltage + (Offset * 4 * 6)`

Am I correct it is the 1st one that I should use.

Ken

Quote:
Am I correct it is the 1st one that I should use.

No. The += will always happen last. In fact, any operator that includes = as an assignment (as opposed to comparison) has the lowest precedence. Aside from that, * has a higher precedence than +, so it would never be interpreted the second way even if you wrote it:
Quote:
Voltage = Voltage + Offset * 6 * 4;

You would have to explicitly use the parens.

Any good C book will give you the full order of precedence of all operators.

Regards,
Steve A.

The Board helps those that help themselves.

Last Edited: Tue. May 1, 2007 - 06:01 AM

Bad guess. Assignment operators are very low precedence. It is equivalent to the second one.

A copy of K&R or a quick google will turn up an operator precedence table for C.

Hi

Thanks for the quick responses.
I knew I might get a bit of flaking here but I did look up some C manuals.
Coming from Pascal, Delphi & Asm, it's a bit hard to wrap my head around it.

Just for the sake of rational.
I set up the constant with "Offset = 20" and "Voltage = 700".
So the procedure is work from the right to the left starting with "*" then "+".

```1) 4 * 6 = 24
2) Offset (20) * 24 = 480
3) Voltage(700) + 480 = 1180```

Correct me if I am wrong.

Ken