I'm still learning C, and wondering which of these 2 are faster/more efficient and better programming practice.
ORCode:#define sq(x) x*x
Code:float sq(float x) { return x * x; }
I'm still learning C, and wondering which of these 2 are faster/more efficient and better programming practice.
ORCode:#define sq(x) x*x
Code:float sq(float x) { return x * x; }
The #define macro is faster, unless the compiler decides to inline the function, in which case they're the same speed.
However, as far as best programming practice is concerned, the function is typically preferred as macros tend to have undesired side effects. Take for instance, if you try: float squared = sq(x++). The preprocessor would expand the statement to float squared = x++ * x++ which results in undefined behavior. You should, at the very least, put parentheses around your macro variables (e.g. #define sq(x) (x) * (x)) to avoid any order of operations induced headaches.
Last edited by itsme86; 11-02-2010 at 06:59 PM.
If you understand what you're doing, you're not learning anything.
Thanks for the quick response.
That's good to know.
But what about the part were the function takes only a float and returns a float. Wouldn't casting or converting numbers to floats be slower than the macro? And doesn't this limit your results lets say if you wanted to square a double?
Well, you could always create a function for each type you want to use: sqf(), sqi(), sqd(), etc.
If you understand what you're doing, you're not learning anything.