473,836 Members | 1,553 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inline functions vs. macros


When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?

What sort of things is it still reasonable to do using macros? For
example, is it reasonable to write type generic functions macros?

#define CUBE(I) ( (I) * (I) * (I) )

Is there some more concise set of things where inline functions should
be used instead of macros? Multi-statement macros, for example?

Thanks,
rCs
Oct 18 '06 #1
33 8912
Robert Seacord <rc*@sei.cmu.ed uwrites:
Is there some more concise set of things where inline functions should
be used instead of macros? Multi-statement macros, for example?
In general, if an inline function can be used, it should be
used. Inline functions are much less likely to cause nasty
surprises than macros, so they are preferred.
--
"The fact that there is a holy war doesn't mean that one of the sides
doesn't suck - usually both do..."
--Alexander Viro
Oct 18 '06 #2
Well, as the majority probably know, macros are really tricky to use
and one should be very careful with them. The best example I know when
they shouldn't be used, is the following:

#define max(a,b) ((a)>(b)?(a):(b ))
int x = 4, y = 5;
int z = max(x++, y++);

One would expect the x and y to be incremented once each, but the fact
is the text renders into the following:
int z = ((x++)>(y++)?(x ++):(y++)),
which means the bigger of the two will get incremented twice instead of
only once.

Robert Seacord wrote:
When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?

What sort of things is it still reasonable to do using macros? For
example, is it reasonable to write type generic functions macros?

#define CUBE(I) ( (I) * (I) * (I) )

Is there some more concise set of things where inline functions should
be used instead of macros? Multi-statement macros, for example?

Thanks,
rCs
Oct 18 '06 #3
Robert Seacord wrote:
When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?
In cases when the both methods are interchangeable - of course, using inline
functions is a better idea.
What sort of things is it still reasonable to do using macros?
There are lots of things that can only be done with macros. Macros can be used
as a substitute for absolutely any piece of code and that means a lot.

For example, one can use macros to generate object and function declarations and
definitions. One can use macros to implement "local functions" (repetitive
pieces of code that have access to automatic variables from the enclosing
scope). Functionality of macros can be used to simulate functionality of
templates in C++.

When macros are used to implement "functions" they can be made to support
certain form of "lazy calculation". For example, the following macro

#define SELECT(s, v1, v2) ((s) ? (v1) : (v2))

will calculate only one of the two expressions depending on the selector's value
(cannot be achieved with an inline function).

And so on. Again, there are lots of other things that can only be done with
macros. One just have to keep in mind that benefits of macros often come with a
considerable number of drawbacks, meaning that one has to use macros with
caution. Nevertheless, the popular belief that macros should be avoided at all
costs makes absolutely no sense. But in situations where macros and inline
functions offer the same functionality it is better to stick with inline functions.
For
example, is it reasonable to write type generic functions macros?

#define CUBE(I) ( (I) * (I) * (I) )
Well, if the key point here is to have a type-generic "function", then it is
reasonable. However, in a simple case like this it might prove to be a better
decision to just write several inline functions with different names. Actually,
macros can still be used to do the latter as shown below:

#define DEFINE_CUBE(T, s) inline T cube_##s(T v) { return v * v * v; }

DEFINE_CUBE(dou ble, d)
DEFINE_CUBE(int , i)
DEFINE_CUBE(uns igned, ui)

--
Best regards,
Andrey Tarasevich
Oct 18 '06 #4
Darko said:
Well, as the majority probably know, macros are really tricky to use
I agree that macros do require a modicum of care, particularly if their
arguments are evaluated more than once, but I wouldn't go so far as to say
they're really tricky. Yes, okay, you can /make/ them tricky, but then you
can make functions tricky, too.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 18 '06 #5

Robert Seacord wrote:
When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?
They're apples versus kittens. About all they have in common is
they're both edible.

With a macro you're assured it's going to get expanded as text right
there. Now is it assured an inline function will get expanded inline?

With a macro you can call it in any context, with or without parens,
and it will generate almost any syntactical mess. A function can only
be used in certain contexts, executable, and must have parens.

macros have their place when you need some bizarre declaration or
executable code.
For instance since C doesnt have a "with" statement, you have to write:

Application->WindowList[ Message->WindowIndex ]->Next->Panel->Title =
"syph";
Application->WindowList[ Message->WindowIndex ]->Next->Panel->Font =
"Aramaic";
Application->WindowList[ Message->WindowIndex ]->Next->Panel->Style =
S_BOLD;
Application->WindowList[ Message->WindowIndex ]->Next->Panel->Align=
AA_RIGHT;

.... which just cries out for some factoring. One way is to (ouch) use
a macro.

Oct 18 '06 #6

Robert Seacord wrote:
When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?

What sort of things is it still reasonable to do using macros? For
example, is it reasonable to write type generic functions macros?

#define CUBE(I) ( (I) * (I) * (I) )
It is, until someone innocently writes

x = CUBE(y++);

and gets undefined behavior for their trouble.
Is there some more concise set of things where inline functions should
be used instead of macros? Multi-statement macros, for example?

Thanks,
rCs
Remember that the C preprocessor is strictly a text substitution
mechanism; it does not know or care about scope, or type, or syntax, or
anything else. Therefore, using preprocessor macros to simulate inline
functions or to fake generic programming is generally a bad idea for
anything other than the most simple of expressions, and even then you
have to beware of situations like the one I describe above.

If you need a function-like operation, then use an actual function,
whether it's inline or not. If you're concerned about efficiency, use
a profiling tool to find the real bottlenecks; don't just blindly
convert functions to macros in the hopes that it will speed things up.

If you want generics, use C++ or some other language that supports
them. Trying to fake it in C is often more trouble than it's worth.

Oct 18 '06 #7
Ancient_Hacker wrote:
Robert Seacord wrote:
>>When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?


They're apples versus kittens. About all they have in common is
they're both edible.

With a macro you're assured it's going to get expanded as text right
there. Now is it assured an inline function will get expanded inline?

With a macro you can call it in any context, with or without parens,
and it will generate almost any syntactical mess. A function can only
be used in certain contexts, executable, and must have parens.

macros have their place when you need some bizarre declaration or
executable code.
For instance since C doesnt have a "with" statement, you have to write:

Application->WindowList[ Message->WindowIndex ]->Next->Panel->Title =
"syph";
Application->WindowList[ Message->WindowIndex ]->Next->Panel->Font =
"Aramaic";
Application->WindowList[ Message->WindowIndex ]->Next->Panel->Style =
S_BOLD;
Application->WindowList[ Message->WindowIndex ]->Next->Panel->Align=
AA_RIGHT;

.... which just cries out for some factoring. One way is to (ouch) use
a macro.
Or
PanelType *panel =
&Application->WindowList[Message->WindowIndex]->Next->Panel;

--
Ian Collins.
Oct 18 '06 #8
Frederick Gotham <fg*******@spam .comwrote:
(1) C90 doesn't support inline.
(2) Even if the compiler _does_ support inline, the code is guaranteed to
^^ isn't
be inlined.
(3) It doesn't yield a compile-time constant.
A macro might not either; much good and evil can be done with macros.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gma il.com | don't, I need to know. Flames welcome.
Oct 18 '06 #9
On Wed, 2006-10-18 at 21:16 +0000, Frederick Gotham wrote:
Robert Seacord posted:
When writing C99 code is a reasonable recommendation to use inline
functions instead of macros?
Not in general, no, for three reasons:

(1) C90 doesn't support inline.
(2) Even if the compiler _does_ support inline, the code is guaranteed to
be inlined.
You meant /not/ guaranteed to be inline. According to C99, that is.

--
Andrew Poelstra <http://www.wpsoftware. net/projects/>

Oct 18 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
6578
by: A | last post by:
Hi, I'm having problems completing a project in C++. I have been using inline functions in some of my header files. I have only done so for simple functions that only have 1 statement (eg. accessor and mutator methods to access private data members). I would like to know if there are any issues with using inline functions that may have attributed to my errors before I start separting them out into "outline functions". Regards
3
1358
by: Peng Yu | last post by:
Hi, I'm trying to define inline_test::test() to be inline. But I always got errors. I know that if I define inline_test::test() in inline_test.h, there are no errors. But I still would rather to put the member functions in *.cc files not the *.h files. Do you know how to do that? The following paragraphs are the compile error and the source codes.
43
13320
by: Patrick Laurent | last post by:
Hello I have a program with many many inlined template functions It is essential for the execution speed that every (or almost every) function marked as inlined, becomes really inlined by the compiler. I already compiled the program with Intel Compiler (ICL) on Visual C++, and it works fine and fast. I verified that the functions are really inlined. But with GCC 3.4 (Linux+Cygwin) or ICC (Linux), The same program is about 5
9
2664
by: Bilgehan.Balban | last post by:
Hi, If I define an inline function in one .c file, and use it from another, after compiling and linking the two, it seems the function is not inlined but rather called as a regular function. I would expect to see it inlined during linkage of the two object files. Does inlining only occur if the inline function is defined within the same file that it is called? Thanks,
12
676
by: sam_cit | last post by:
Hi Everyone, I have few questions on inline functions, when i declare a function as inline, is it for sure that the compiler would replace the function call with the actual body of the function? or is it a call taken by compiler? Second, i see that it is same as what Macro's used to do for c, if so what is the advantage for going in for inline functions than to Macros?
37
9013
by: junky_fellow | last post by:
hi guys, Can you please suggest that in what cases should a macro be preferred over inline function and viceversa ? Is there any case where using a macro will be more efficient as compared to inline function ? thanks for any help in advance ...
2
3284
by: subramanian100in | last post by:
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.
15
2640
by: Mahesh | last post by:
Hi, I need to know if stack frames are generated in case of a inline function execution or do they execute just like macros? if they execute like macros, then what is the need for having inline function? where would you use macros and where inlines? Thanks Mahesh
6
4069
by: Laurent Deniau | last post by:
When I compile the code below with gcc -std=c99 -W -Wall -pedantic -O3 -Winline, it reports the following: variadic.c: In function fv: variadic.c:12: warning: function fv can never be inlined because it uses variable argument lists variadic.c: In function vf: variadic.c:12: warning: inlining failed in call to fv: function not inlinable variadic.c:27: warning: called from here
0
10838
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10544
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10250
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7788
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6977
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5645
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4447
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4010
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3111
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.