xaphod
xaphod

Reputation: 6804

Why do brackets mess up this math in objective-c?

Why do the two calculations have differing results? This is xcode 6.1.

(lldb) print newBounds.size.height
(CGFloat) $0 = 446.5
(lldb) print newBounds.size.height * 6/4
(double) $1 = 669.75
(lldb) print newBounds.size.height * (6/4)
(double) $2 = 446.5

Upvotes: 0

Views: 64

Answers (1)

Paul R
Paul R

Reputation: 212959

It's just integer math and the usual rules for promotion of types.

height * 6/4 == (height * (double)6) / (double)4 == (height * 6.0) / 4.0

whereas:

height * (6/4) == height * (double)(1) == height * 1.0

since 6/4 == 1 and the parentheses force this to be evaluated first before promoting it to double.

This is the same behaviour as in C, C++, Objective-C, et al, so you shouldn't be too surprised to see it in your debugger too.

Upvotes: 5

Related Questions