Why and when do you use the define directive?

1 answer

Answer

1130066

2026-05-10 09:30

+ Follow

The #define preprocessor directive is severely overused in my opinion.

Often, you will see programmers write something like this:

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

However doing so is rather dangerous, because the preprocessor replaces things textually.

This means that if you pass in a call to a function, it may happen twice, for example:

MAX(++i, j) will be expanded to

(((++i) > (j))? (++i) : (j))

which is bad.

A much safer (and more common) example is that people will use #define to create a constant variable:

#define MYCONST 10

This too can cause problems if another file depends on the constant and certain other conditions are met.

A safer alternative is to declare a const variable.

The one advantage of using #define for literal constants is that the number will not be stored in memory attached to an object like a const variable will.

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.