Operators Precedence Query

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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.

Please advise.

Ken

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

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

So my answer is 1180.

Correct me if I am wrong.

Ken

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The only thing you REALLY need to know about precendence are that parentheses are higher than anything else. If in doubt just add in some brackets!

Cliff

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi

Will bear that in mind about the brackets.
Thanks to all.

Ken