Can somebody explain the difference between Macros and Procedures, and also when you would use one versus the other. It seems to me like Procedures would be better, because the macro would be inserted inside the code every time you call it, where as the procedure is just in one spot.
Macros and procedures are both a mechanism for reusing code. The main difference between the two is when the reuse occurs.

The code in a macro is reused when the source code is compiled. Defining a macro has no immediate effect on the compiled code, but then using that macro is like copying and pasting the body of the macro at the current source code location. While the source code can succinctly reuse the code, each use will be expanded out in-place in the compiled code. At runtime, there is no overhead to invoke this code because it has been copied directly into its use site, but for all but the smallest macros, this can result in an unnecessary increase in the size of the compiled code.

The code in a procedure (more commonly called a "routine" or "function") is reused only when the compiled program is running. Only one copy of the body will exist in the compiled code (where it is defined). Because this code will not have been copied directly into each use site, the use site will have call the routine, and when it's done, the routine will have to return to the use site. This incurs a small overhead, but provided the routine is more than just a few bytes large (and is used more than once), the compiled code size savings is usually worth it.

There are other more nuanced strengths of each, as well. For example, a macro can perform some computations at compile-time instead of runtime, making compiled code smaller and faster. On the other side, a routine can be provided by a third party at runtime, allowing its implementation to be improved in the third party code without you needing to change or even recompile your code.

Unless you have a particular reason to use a macro rather than a routine, you should probably just use a routine.
Okay, thank you!
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
Page 1 of 1
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement