Roger
Roger

Reputation: 7610

Whats the difference between func(160.0-90.0) and func((160.0-90.0)) (macro)?

I'm clueless, why two extra braces when giving parameters to a macro have different results.

Given the following macro:

#define   DEGREES_TO_RADIANS(degrees)  ((M_PI * degrees)/ 180)

Why the following code:

NSLog(@"test 1: %f", DEGREES_TO_RADIANS(70.0));
NSLog(@"test 2: %f", DEGREES_TO_RADIANS(160.0-90.0));
NSLog(@"test 3: %f", DEGREES_TO_RADIANS((160.0-90.0)));

Has different results:

2012-12-05 00:43:07.177 test[9267:11603] test 1: 1.221730
2012-12-05 00:43:07.179 test[9267:11603] test 2: 2.292527
2012-12-05 00:43:07.180 test[9267:11603] test 3: 1.221730

Test 1 & 3 are correct. But why 'test 2' has a wrong answer, beats me. Maybe one of guru's can shed some light on this.

Thanks!

Upvotes: 1

Views: 61

Answers (1)

William Pursell
William Pursell

Reputation: 212634

Because M_PI * 160.0 - 90.0 != M_PI * (160.0-90.0)

This is precisely why it is highly recommended to write the macro with parentheses:

#define   DEGREES_TO_RADIANS(degrees)  ((M_PI * (degrees))/ 180)

Upvotes: 5

Related Questions