Why Is #Define Bad and What Is the Proper Substitute

Why is #define bad and what is the proper substitute?

Define it as a constant variable. It is a good programming practice.

const wchar_t *dItemName = L"CellPhone";

In case you need to know the lenght of your string somewhere later, then define it as an array:

const wchar_t dItemName[] = L"CellPhone";

Also, why #define is bad: It transforms all places where you use word dItemName to L"CellPhone". Example:

struct {
int dItemName;
} SomeStruct;

will become invalid:

struct {
int L"CellPhone";
} SomeStruct;

Alternatives to using #define in C++? Why is it frowned upon?

Why is this this code bad?

Because VERSION can be overwritten and the compiler won't tell you.

Is there an alternative to using #define?

const char * VERSION = "1.2";

or

const std::string VERSION = "1.2";

Why are preprocessor macros evil and what are the alternatives?

Macros are just like any other tool - a hammer used in a murder is not evil because it's a hammer. It is evil in the way the person uses it in that way. If you want to hammer in nails, a hammer is a perfect tool.

There are a few aspects to macros that make them "bad" (I'll expand on each later, and suggest alternatives):

  1. You can not debug macros.
  2. Macro expansion can lead to strange side effects.
  3. Macros have no "namespace", so if you have a macro that clashes with a name used elsewhere, you get macro replacements where you didn't want it, and this usually leads to strange error messages.
  4. Macros may affect things you don't realize.

So let's expand a little here:

1) Macros can't be debugged.
When you have a macro that translates to a number or a string, the source code will have the macro name, and many debuggers can't "see" what the macro translates to. So you don't actually know what is going on.

Replacement: Use enum or const T

For "function-like" macros, because the debugger works on a "per source line where you are" level, your macro will act like a single statement, no matter if it's one statement or a hundred. Makes it hard to figure out what is going on.

Replacement: Use functions - inline if it needs to be "fast" (but beware that too much inline is not a good thing)

2) Macro expansions can have strange side effects.

The famous one is #define SQUARE(x) ((x) * (x)) and the use x2 = SQUARE(x++). That leads to x2 = (x++) * (x++);, which, even if it was valid code [1], would almost certainly not be what the programmer wanted. If it was a function, it would be fine to do x++, and x would only increment once.

Another example is "if else" in macros, say we have this:

#define safe_divide(res, x, y)   if (y != 0) res = x/y;

and then

if (something) safe_divide(b, a, x);
else printf("Something is not set...");

It actually becomes completely the wrong thing....

Replacement: real functions.

3) Macros have no namespace

If we have a macro:

#define begin() x = 0

and we have some code in C++ that uses begin:

std::vector<int> v;

... stuff is loaded into v ...

for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
std::cout << ' ' << *it;

Now, what error message do you think you get, and where do you look for an error [assuming you have completely forgotten - or didn't even know about - the begin macro that lives in some header file that someone else wrote? [and even more fun if you included that macro before the include - you'd be drowning in strange errors that makes absolutely no sense when you look at the code itself.

Replacement: Well there isn't so much as a replacement as a "rule" - only use uppercase names for macros, and never use all uppercase names for other things.

4) Macros have effects you don't realize

Take this function:

#define begin() x = 0
#define end() x = 17
... a few thousand lines of stuff here ...
void dostuff()
{
int x = 7;

begin();

... more code using x ...

printf("x=%d\n", x);

end();

}

Now, without looking at the macro, you would think that begin is a function, which shouldn't affect x.

This sort of thing, and I've seen much more complex examples, can REALLY mess up your day!

Replacement: Either don't use a macro to set x, or pass x in as an argument.

There are times when using macros is definitely beneficial. One example is to wrap a function with macros to pass on file/line information:

#define malloc(x) my_debug_malloc(x, __FILE__, __LINE__)
#define free(x) my_debug_free(x, __FILE__, __LINE__)

Now we can use my_debug_malloc as the regular malloc in the code, but it has extra arguments, so when it comes to the end and we scan the "which memory elements hasn't been freed", we can print where the allocation was made so the programmer can track down the leak.

[1] It is undefined behaviour to update one variable more than once "in a sequence point". A sequence point is not exactly the same as a statement, but for most intents and purposes, that's what we should consider it as. So doing x++ * x++ will update x twice, which is undefined and will probably lead to different values on different systems, and different outcome value in x as well.

In C++, is it better to use #define or const to avoid magic numbers?

Don't worry about efficiency in this case since all of them will be computed in compile-time.

You should stop using Macros (at least to define constants) whenever you can. Macros are wild things against namespaces and scopes. On the other hand const objects have type and this can reduce unintended mistakes.

It's always useful to read Stroustrup's piece of advises: "So, what's wrong with using macros?"

Why would someone use #define to define constants?

#define has many different applications, but your question seems to be about one specific application: defining named constants.

In C++ there's rarely a reason to use #define to define named constants.

#define is normally widely used in C code, since C language is significantly different from C++ when it comes to defining constants. In short, const int objects are not constants in C, which means that in C the primary way to define a true constant is to use #define. (Also, for int constants one can use enums).

Is there a good reason for always enclosing a define in parentheses in C?

Yes. The preprocessor concatenation operator (##) will cause issues, for example:

#define _add_penguin(a) penguin ## a
#define add_penguin(a) _add_penguin(a)

#define WIDTH (100)
#define HEIGHT 200

add_penguin(HEIGHT) // expands to penguin200
add_penguin(WIDTH) // error, cannot concatenate penguin and (100)

Same for stringization (#). Clearly this is a corner case and probably doesn't matter considering how WIDTH will presumably be used. Still, it is something to keep in mind about the preprocessor.

(The reason why adding the second penguin fails is a subtle detail of the preprocessing rules in C99 - iirc it fails because concatenating to two non-placeholder preprocessing tokens must always result in a single preprocessing token - but this is irrelevant, even if the concatenation was allowed it would still give a different result than the unbracketed #define!).

All other responses are correct only insofar that it doesn't matter from the point of view of the C++ scanner because, indeed, a number is atomic. However, to my reading of the question there is no sign that only cases with no further preprocessor expansion should be considered, so the other responses are, even though I totally agree with the advice contained therein, wrong.

Replacing define statement with actual code

The following is probably similar in principle to your code.
It is solved with #define and sets a serialno to each Object and prints something out to the console:

#define True GetObject(true)
#define False GetObject(false)

#include <iostream>
using namespace std;

class Object {
public:
Object(bool b, int serial) : _b(b), _serialno(serial) {};

bool _b;
int _serialno;
};

Object GetObject(bool b) {
static int curserial = 0;

Object result(b, ++curserial);

cout << "Created Object with serialno " << result._serialno << " and value " << boolalpha << result._b << endl;
return result;
}

int main() {
auto c = True;
auto d = True;
auto e = False;

return 0;
}

which generates the output

Created Object with serialno 1 and value true
Created Object with serialno 2 and value true
Created Object with serialno 3 and value false

Now we change it to the same result without '#define':

#include <iostream>
using namespace std;

class Object;
void GotObject(Object& o);

class Object {
public:
Object(bool b) : _b(b), _serialno(++curserial) {};
Object(const Object& other) : _b(other._b), _serialno(++curserial) {
GotObject(*this);
};

bool _b;
int _serialno;

inline static int curserial = 0;
};

void GotObject(Object& o) {
cout << "Created Object with serialno " << o._serialno << " and value " << boolalpha << o._b << endl;
}

inline Object True(true);
inline Object False(false);

int main() {
auto c = True;
auto d = True;
auto e = False;

return 0;
}

Output:

Created Object with serialno 3 and value true
Created Object with serialno 4 and value true
Created Object with serialno 5 and value false

Each time we assign the values of True or False to new variables the copy constructor is called and can do, whatever you did in GetObject.

Small variant: If we choose this alternative custom constructor instead of the one in the code,

    Object(bool b) : _b(b), _serialno(0) {};

we would get as output:

Created Object with serialno 1 and value true
Created Object with serialno 2 and value true
Created Object with serialno 3 and value false

The difference is, whether the serialno is also counted up for True and False themselves or only after assigning those to a variable.

For Generating True and False the first constructor is called, for the following assignments to other variables, the second constructor.

You could also keep a bool _original variable inside Object to only call GetObject(), which states whether you copy from the original True or False. It is true only for True and False. You can recognize those by them calling a special constructor. If you want to make it safe to use, you can make that constructor private, so it can only be called by friend functions or by static factory methods.

In the following code, GotObject is not called from assigning from c to f.

#include <iostream>
using namespace std;

class Object;
void GotObject(Object& o);

class Object {
public:
Object(bool b) : _b(b), _serialno(0), _original(true) {};
Object(const Object& other) : _b(other._b), _original(false), _serialno(0) {
if (other._original)
GotObject(*this);
};

bool _original;
bool _b;
int _serialno;
};

void GotObject(Object& o) {
static int curserial = 0;
o._serialno = ++curserial;

cout << "Created Object with serialno " << o._serialno << " and value " << boolalpha << o._b << endl;
}

inline Object True(true);
inline Object False(false);

int main() {
auto c = True;
auto d = True;
auto e = False;
auto f = c;

return 0;
}

Output:

Created Object with serialno 1 and value true
Created Object with serialno 2 and value true
Created Object with serialno 3 and value false

Difference between preprocessor macros and std::source_location

Preprocessor macros live outside the type system. Preprocessor macro substitution happens outside the rest of the language. See this answer and this answer for a comprehensive discussion of the disadvantages of using the preprocessor.

std::source_location on the other hand behaves like any other C++ struct. It has plain value fields that are typed and behave like any other values in the language.

Besides that, functionality-wise the two mechanisms are equivalent. There is nothing that the one can achieve that cannot be done by the other (apart from the column field in source_location, which has no equivalent in the preprocessor). It's just that the new approach achieves its goals more nicely.

define / use a Macro inside a fcuntion - good style/practice?

Alternate solution:

#include <stdbool.h>

void DeviceOn(void)
{
uint8_t DIOPort = ReadDIOPort();

bool PowerIsOK = DIOPort & 1 << SENSOR1;
bool SafetyIsOK = ! (DIOPort & 1 << SENSOR2);
bool LightIsOn = DIOPort & 1 << SENSOR3;
bool CoffeeMugIsFull = DIOPort & 1 << SENSOR4;

if (PowerISOK && SafetyIsOK && LightIsOn && CoffeeMugIsFull)
turnOnDevice();
else
turnOffDevice();
}


Related Topics



Leave a reply



Submit