Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference in practice between inline and #define?

As the title says; what's the difference in practice between the inline keyword and the #define preprocessor directive?

like image 289
eliego Avatar asked Aug 24 '10 08:08

eliego


2 Answers

#define is a preprocessor tool and has macro semantics. Consider this, if max(a,b) is a macro defined as

#define max(a,b) ((a)>(b)?(a):(b)):

Ex 1:

val = max(100, GetBloodSample(BS_LDL)) would spill extra innocent blood, because the function will actually be called twice. This might mean significant performance difference for real applications.

Ex 2:

val = max(3, schroedingerCat.GetNumPaws()) This demonstrates a serious difference in program logic, because this can unexpectedly return a number which is less than 3 - something the user would not expect.

Ex 3:

val = max(x, y++) might increment y more than one time.


With inline functions, none of these will happen.

The main reason is that macro concept targets transparency of implementation (textual code replace) and inline targets proper language concepts, making the invocation semantics more transparent to the user.

like image 129
Pavel Radzivilovsky Avatar answered Oct 10 '22 10:10

Pavel Radzivilovsky


Macros (created with #define) are always replaced as written, and can have double-evaluation problems.

inline on the other hand, is purely advisory - the compiler is free to ignore it. Under the C99 standard, an inline function can also have external linkage, creating a function definition which can be linked against.

like image 2
caf Avatar answered Oct 10 '22 10:10

caf