Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DEFINE() macro usage in expressinions

So I defined..

#define RADIAN(x) x*3.14159265f/180.0f

and then used it like this:

RADIAN(theta-90)

My program constantly gave me incorrect results, it took me a couple hours to realize that there was a huge difference between the above statement and the statement below.

RADIAN((theta-90))

Now my program is running perfectly fine. Why is the first statement incorrect?

like image 388
xorxorxor Avatar asked Dec 07 '25 10:12

xorxorxor


2 Answers

#define makes just text substitution, so RADIAN(theta-90) was really theta-90*3.14159265f/180.0f, what obviously wasn't what you meant. Try

#define RADIAN(x) ((x)*3.14159265f/180.0f)

instead.

like image 163
x13n Avatar answered Dec 10 '25 00:12

x13n


Macro's largley do text based replacement so

RADIAN(theta-90) 

expands to:

theta - 90* 3.14159265f/180.0f  

which because of operator precedence, evaluates as:

theta - (90* 3.14159265f/180.0f)  
like image 39
forsvarir Avatar answered Dec 10 '25 00:12

forsvarir