Thread: Which is faster?

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    11

    Which is faster?

    I'm still learning C, and wondering which of these 2 are faster/more efficient and better programming practice.

    Code:
    #define sq(x) x*x
    OR

    Code:
    float sq(float x) { return x * x; }

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    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.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    11
    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?

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What is faster and is there any difference?
    By yann in forum C++ Programming
    Replies: 10
    Last Post: 10-10-2010, 01:59 AM
  2. Faster bitwise operator
    By Yarin in forum C++ Programming
    Replies: 18
    Last Post: 04-29-2009, 01:56 PM
  3. Faster way of printing to the screen
    By cacophonix in forum C Programming
    Replies: 16
    Last Post: 02-04-2009, 01:18 PM
  4. does const make functions faster?
    By MathFan in forum C++ Programming
    Replies: 7
    Last Post: 04-25-2005, 09:03 AM
  5. Floating point faster than fixed-point
    By VirtualAce in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 11-08-2001, 11:34 PM