inline function vs function-like macro

  • Thread starter subramanian100in
  • Start date
S

subramanian100in

Suppose I am using a compiler which is C99 compliant.

Function-like macros have the disadvantage if an argument with side-
effects is passed.
For example,

#define SQUARE(x) ( (x) * (x) )

If SQUARE(x++) is called, it results in undefined behaviour.

Instead we can use the C99 feature of inline function. Am I correct ?

Given this, is there any reason for still preferring function-like
macros over inline function feature of C99 ?
 
S

santosh

Suppose I am using a compiler which is C99 compliant.

Function-like macros have the disadvantage if an argument with side-
effects is passed.
For example,

#define SQUARE(x) ( (x) * (x) )

If SQUARE(x++) is called, it results in undefined behaviour.

Instead we can use the C99 feature of inline function. Am I correct ?

Given this, is there any reason for still preferring function-like
macros over inline function feature of C99 ?

Yes. Macros allow use without regard to type checking. Because they're
a compile-time feature, they can be used to do certain things that
would not be possible with functions. But more importantly, inline is
a C99 feature and is not very portable across a wide range of
compilers.

Also inline specifies to the compiler to make access to the function
as fast as possible, but doesn't actually require it to embed the code
for the function, wherever it's called, unlike with macros.
 
F

Flash Gordon

Suppose I am using a compiler which is C99 compliant.

Function-like macros have the disadvantage if an argument with side-
effects is passed.
For example,

#define SQUARE(x) ( (x) * (x) )

If SQUARE(x++) is called, it results in undefined behaviour.

Instead we can use the C99 feature of inline function. Am I correct ?

Yes, given certain limitations.
Given this, is there any reason for still preferring function-like
macros over inline function feature of C99 ?

Yes, in certain situations. Taking your example, you can pass an int,
double or any other numeric type to SQUARE and it will "do the right
thing"(tm). However, if you use inline functions and you want to be able
to use it on all types without converting ints to doubles, or even a
complex type you will have to write squarei, squarel, squared, squarecd
etc. and call the correct one. Not always an issue, but a point to bare
in mind.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top