30

What's the precedence in the next expression?

item = (char*)heap + offset;

Is it (char*)(heap + offset) or ((char*)heap) + offset?

Jacob
  • 34,255
  • 14
  • 110
  • 165
Cheery
  • 24,645
  • 16
  • 59
  • 83

4 Answers4

36

Cast trumps binary addition according to the precedence table.

Precedence Table

Alexander Ushakov
  • 5,139
  • 3
  • 27
  • 50
Jacob
  • 34,255
  • 14
  • 110
  • 165
8

It's ((char *)heap) + offset. Casts have much higher precedence than addition.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 2
    This is quite correct, but if it's really unclear to the coder, then I'd recommend actually using the parentheses as shown here. – Steven Sudit Jul 28 '10 at 15:29
  • 4
    The problem rises when the original author coder doesn't have precedence order doubts in the case, but another maintenance coder has. – Spidey Apr 12 '12 at 18:59
2
((char*)heap) + offset
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
1

The cast is done first, since it has a much higher precedence.

You can look that up in the C precedence table: C precedence table

ib.
  • 27,830
  • 11
  • 80
  • 100
Alexander Grass
  • 384
  • 2
  • 11