Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

#define dItemName        L"CellPhone"
like image 689
Christopher Peterson Avatar asked Jan 17 '11 17:01

Christopher Peterson


2 Answers

#define is a preprocessor instruction that defines a macro. In your case macro dItemName with value L"CellPhone".

Macros are bad mostly because they are processed before the actual code is. This means that they aren't subjected to scopes and to the rules of C++ syntax. If you've got a variable somewhere called dItemName, things won't probably work: you'll get hard-to-understand compilation errors due to that.

The solution is to declare dItemName as a variable (in this case a const variable).

like image 173
peoro Avatar answered Oct 05 '22 22:10

peoro


Pointing to define doing what they where invented for as a failure is - well blaming a knife for cutting.

If you dont not properly Name your defines with UPPERCASE_NAMES you will have troubles, but you will have those troubles anyway in C if you can not self-discipline your working style.

You can not use const to generate dynamically rearranging systems, so its not suited for any embedded Application that is tailored pre-compile to usage.Const can only be assigned pre-evaluation constants, so not even other const Expressions.

Just because a Tool doese not bow to the OO-Paradigm its does not suddenly become useless. Const is not equal replacement regarding functionality.

like image 28
Pica Avatar answered Oct 06 '22 00:10

Pica