When to use macros.

P

prashant.khade1623

HI All,

I know the clear distinction between macro and function.

I know that macro will speed up the program and using function will
reduce the size.

But how do we know when to use macro and function. ?
 
I

Ian Collins

HI All,

I know the clear distinction between macro and function.

I know that macro will speed up the program and using function will
reduce the size.

But how do we know when to use macro and function. ?

Use a function when you can, use a macro when all else fails. Modern
compilers do a good job of inlining short functions, so function like
macros are only really useful to implement a poor man's function
overloading.
 
B

Ben Bacarisse

Richard Heathfield said:
(e-mail address removed) said:

Insofar as this is true, it is because macros are expanded inline
(increasing the size of the program with every expansion, but eliminating
the overhead of a function call). In C99, functions can be inlined too (at
the compiler's discretion).

Can't functions be inlined in C90 (at the compiler's discretion)?
 
D

Default User

Ian said:
Use a function when you can, use a macro when all else fails. Modern
compilers do a good job of inlining short functions, so function like
macros are only really useful to implement a poor man's function
overloading.


They are also useful for switchable behavior. As an example, you can
have extra diagnostic "functions" embedded for development, then turn
them off for release code. Naturally, you could do the same thing with
#if blocks around real function calls, but that tends to look a bit
more confusing.



Brian
 
H

Herbert Rosenau

HI All,

I know the clear distinction between macro and function.

I know that macro will speed up the program and using function will
reduce the size.

But how do we know when to use macro and function. ?

On modern compilers a function that can be inlined is to prefere over
a macro because it adds type security.

As a macro is only text replacement it can very useful when the only
difference between different functions is only a single statement or
different types on the same functionality.

A macro with parameters fails miserably on having usage of side
effects like pre/post increment on its opreands, an inlided function
avoids that.

I prefere functions over macros. On other hand I write a macro instead
of a function when I have to do the same little piece of code with
different data types.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2R Deutsch ist da!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,201
Latest member
KourtneyBe

Latest Threads

Top