Related
How may I prevent hard coded numbers in C++?
For example if I have Score+=10;
In C I would do:
#define FACTOR 10
Score+=FACTOR
But In C++ my professor told we don't use #define anymore (It's a C thing and risky), So what should I use?
You can use enum or const int, but I see nothing wrong with #define in that particular example and I prefer to use #define
I hope your professor is allowing you to use C++17/20 or at least C++11.
If that's the case, you best use constexpr for every constant.
constexpr auto FACTOR = 10;
From C++17 on, you can even use this to create classes as constants within class/struct scope without ODR violations.
struct S
{
constexpr static std::string_view STR = "str"sv;
};
1.Doesn't belong to namespaces, and cannot be kept in namespaces.
macro named "max" (as windows.h does), and you try to use std::max(a,b), then at least some compilers will still do macro substitution, giving something like std::(a<b?b:a),
2.Debugging is Difficult in #define since it is a pre processor runs before the execution of code.
This question already has answers here:
What is the difference between #define and const? [duplicate]
(6 answers)
Closed 9 years ago.
The macro #define MAX 80 is equivalent to const int MAX = 80; Both are constant and cannot be modified.
Isn't it better to use the macro instead of the constant integer? The constant integer takes memory. The macro's name is replaced by its value by the pre-processor, right? So it wouldn't take memory.
Why would I use const int rather than the macro?
Reason #1: Scoping. Macros totally ignore scope.
namespace SomeNS {
enum Functor {
MIN = 0
, AVG = 1
, MAX = 2
};
}
If the above code happens to be included in a file after the definition of the MAX macro, it will happily get preprocessed into 80 = 2, and fail compiling spectacularly.
Additionally, const variables are type safe, can be safely initialised with constant expressions (without need for parentheses) etc.
Also note that when the compiler has access to the const variable's definition when using it, it's allowed to "inline" its value. So if you never take its address, it does no even need not take up space.
There are a few reasons actually :
Scoping : you can't define a scope for a macro. It is present at global scope, period. Thus you can't have class-specific constants, you can't have private constants, etc. Also, you could end up with name collision, if you end up declaring something with the same name of a macro that you don't even know exists (in some lib/header you included f.e.)
Debugging : as the preprocessor just replaces instances of the macro with its value, it can become tricky to know why you got an error with a specific value (or just a specific behavior that you didn't expect...) . You have to remember where this value comes from. It is even more important in the case of reusable code, as you can even don't understand where does a value comes from, if it has been defined as a macro in a header you didn't write (thus it's not very good to do this yourself)
Adresses : a const variable is, well, a variable. It means notably that you can pass its adress around (when const pointers or const reference are needed), but you can't with macro
Type safety : you can specify a type for a const variable, something you can't for a macro.
As a general rule, I'd say that (in my opinion) you should avoid #define directives when you have a clear alternative (i.e. const variables, enums, inlines).
The thing is they aren't the same. The macro is just text substitution by the preprocessor while the const is a normal variable.
If someone ever tries to shadow MAX within a function (like const in MAX = 32;) they get a really weird error message when MAX is a macro.
In C++ the language-idiomatic approach is to use constants rather than macros. Trying to save a few bytes of memory (if it even saves them) doesn't seem worth the cost in readability.
1) Debugging is the main one for me. It's difficult for a debugger to resolve MAX to the value at run time, but it can do it with the const int version.
2) You don't get any type information with #define. If you're using a template-based function; say std::max where your other datum is a const int then the macro version will fail but the const int version will not. To work around that you'd have to use #define MAX 80U which is ugly.
3) You cannot control scoping with #define; it will apply to the whole compilation unit following the #define statement.
Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?
What are advantages/disadvantages for each method?
Pros and cons between #defines, consts and (what you have forgot) enums, depending on usage:
enums:
only possible for integer values
properly scoped / identifier clash issues handled nicely, particularly in C++11 enum classes where the enumerations for enum class X are disambiguated by the scope X::
strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control in C++03 (though you can specify a bit field into which they should be packed if the enum is a member of struct/class/union), while C++11 defaults to int but can be explicitly set by the programmer
can't take the address - there isn't one as the enumeration values are effectively substituted inline at the points of usage
stronger usage restraints (e.g. incrementing - template <typename T> void f(T t) { cout << ++t; } won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)
each constant's type taken from the enclosing enum, so template <typename T> void f(T) get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.
even with typeof/decltype, can't expect numeric_limits to provide useful insight into the set of meaningful values and combinations (indeed, "legal" combinations aren't even notated in the source code, consider enum { A = 1, B = 2 } - is A|B "legal" from a program logic perspective?)
the enum's typename may appear in various places in RTTI, compiler messages etc. - possibly useful, possibly obfuscation
you can't use an enumeration without the translation unit actually seeing the value, which means enums in library APIs need the values exposed in the header, and make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
consts:
properly scoped / identifier clash issues handled nicely
strong, single, user-specified type
you might try to "type" a #define ala #define S std::string("abc"), but the constant avoids repeated construction of distinct temporaries at each point of use
One Definition Rule complications
can take address, create const references to them etc.
most similar to a non-const value, which minimises work and impact if switching between the two
value can be placed inside the implementation file, allowing a localised recompile and just client links to pick up the change
#defines:
"global" scope / more prone to conflicting usages, which can produce hard-to-resolve compilation issues and unexpected run-time results rather than sane error messages; mitigating this requires:
long, obscure and/or centrally coordinated identifiers, and access to them can't benefit from implicitly matching used/current/Koenig-looked-up namespace, namespace aliases etc.
while the trumping best-practice allows template parameter identifiers to be single-character uppercase letters (possibly followed by a number), other use of identifiers without lowercase letters is conventionally reserved for and expected of preprocessor defines (outside the OS and C/C++ library headers). This is important for enterprise scale preprocessor usage to remain manageable. 3rd party libraries can be expected to comply. Observing this implies migration of existing consts or enums to/from defines involves a change in capitalisation, and hence requires edits to client source code rather than a "simple" recompile. (Personally, I capitalise the first letter of enumerations but not consts, so I'd be hit migrating between those two too - maybe time to rethink that.)
more compile-time operations possible: string literal concatenation, stringification (taking size thereof), concatenation into identifiers
downside is that given #define X "x" and some client usage ala "pre" X "post", if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char* or const std::string given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post" for string)
can't use sizeof directly on a defined numeric literal
untyped (GCC doesn't warn if compared to unsigned)
some compiler/linker/debugger chains may not present the identifier, so you'll be reduced to looking at "magic numbers" (strings, whatever...)
can't take the address
the substituted value need not be legal (or discrete) in the context where the #define is created, as it's evaluated at each point of use, so you can reference not-yet-declared objects, depend on "implementation" that needn't be pre-included, create "constants" such as { 1, 2 } that can be used to initialise arrays, or #define MICROSECONDS *1E-6 etc. (definitely not recommending this!)
some special things like __FILE__ and __LINE__ can be incorporated into the macro substitution
you can test for existence and value in #if statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef-ine, redefine etc.
substituted text has to be exposed:
in the translation unit it's used by, which means macros in libraries for client use must be in the header, so make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
or on the command line, where even more care is needed to make sure client code is recompiled (e.g. the Makefile or script supplying the definition should be listed as a dependency)
My personal opinion:
As a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).
Personally, I loathe the preprocessor, so I'd always go with const.
The main advantage to a #define is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings.
Advantages of "const"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed.
I don't know exactly what you are getting at with the "static" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using static. For example
namespace {
unsigned const seconds_per_minute = 60;
};
int main (int argc; char *argv[]) {
...
}
If this is a C++ question and it mentions #define as an alternative, then it is about "global" (i.e. file-scope) constants, not about class members. When it comes to such constants in C++ static const is redundant. In C++ const have internal linkage by default and there's no point in declaring them static. So it is really about const vs. #define.
And, finally, in C++ const is preferable. At least because such constants are typed and scoped. There are simply no reasons to prefer #define over const, aside from few exceptions.
String constants, BTW, are one example of such an exception. With #defined string constants one can use compile-time concatenation feature of C/C++ compilers, as in
#define OUT_NAME "output"
#define LOG_EXT ".log"
#define TEXT_EXT ".txt"
const char *const log_file_name = OUT_NAME LOG_EXT;
const char *const text_file_name = OUT_NAME TEXT_EXT;
P.S. Again, just in case, when someone mentions static const as an alternative to #define, it usually means that they are talking about C, not about C++. I wonder whether this question is tagged properly...
#define can lead to unexpected results:
#include <iostream>
#define x 500
#define y x + 5
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
Outputs an incorrect result:
y is 505
z is 510
However, if you replace this with constants:
#include <iostream>
const int x = 500;
const int y = x + 5;
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
It outputs the correct result:
y is 505
z is 1010
This is because #define simply replaces the text. Because doing this can seriously mess up order of operations, I would recommend using a constant variable instead.
Using a static const is like using any other const variables in your code. This means you can trace wherever the information comes from, as opposed to a #define that will simply be replaced in the code in the pre-compilation process.
You might want to take a look at the C++ FAQ Lite for this question:
http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
A static const is typed (it has a type) and can be checked by the compiler for validity, redefinition etc.
a #define can be redifined undefined whatever.
Usually you should prefer static consts. It has no disadvantage. The prprocessor should mainly be used for conditional compilation (and sometimes for really dirty trics maybe).
Defining constants by using preprocessor directive #define is not recommended to apply not only in C++, but also in C. These constants will not have the type. Even in C was proposed to use const for constants.
Always prefer to use the language features over some additional tools like preprocessor.
ES.31: Don't use macros for constants or "functions"
Macros are a major source of bugs. Macros don't obey the usual scope
and type rules. Macros don't obey the usual rules for argument
passing. Macros ensure that the human reader sees something different
from what the compiler sees. Macros complicate tool building.
From C++ Core Guidelines
As a rather old and rusty C programmer who never quite made it fully to C++ because other things came along and is now hacking along getting to grips with Arduino my view is simple.
#define is a compiler pre processor directive and should be used as such, for conditional compilation etc.. E.g. where low level code needs to define some possible alternative data structures for portability to specif hardware. It can produce inconsistent results depending on the order your modules are compiled and linked. If you need something to be global in scope then define it properly as such.
const and (static const) should always be used to name static values or strings. They are typed and safe and the debugger can work fully with them.
enums have always confused me, so I have managed to avoid them.
Please see here: static const vs define
usually a const declaration (notice it doesn't need to be static) is the way to go
If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialize this const member variable in the initialization list).
I have always asked this but I have never received a really good answer; I think that almost any programmer before even writing the first "Hello World" had encountered a phrase like "macro should never be used", "macro are evil" and so on, my question is: why? With the new C++11 is there a real alternative after so many years?
The easy part is about macros like #pragma, that are platform specific and compiler specific, and most of the time they have serious flaws like #pragma once that is error prone in at least 2 important situation: same name in different paths and with some network setups and filesystems.
But in general, what about macros and alternatives to their usage?
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):
You can not debug macros.
Macro expansion can lead to strange side effects.
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.
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.
The saying "macros are evil" usually refers to the use of #define, not #pragma.
Specifically, the expression refers to these two cases:
defining magic numbers as macros
using macros to replace expressions
with the new C++ 11 there is a real alternative after so many years ?
Yes, for the items in the list above (magic numbers should be defined with const/constexpr and expressions should be defined with [normal/inline/template/inline template] functions.
Here are some of the problems introduced by defining magic numbers as macros and replacind expressions with macros (instead of defining functions for evaluating those expressions):
when defining macros for magic numbers, the compiler retains no type information for the defined values. This can cause compilation warnings (and errors) and confuse people debugging the code.
when defining macros instead of functions, programmers using that code expect them to work like functions and they do not.
Consider this code:
#define max(a, b) ( ((a) > (b)) ? (a) : (b) )
int a = 5;
int b = 4;
int c = max(++a, b);
You would expect a and c to be 6 after the assignment to c (as it would, with using std::max instead of the macro). Instead, the code performs:
int c = ( ((++a) ? (b)) ? (++a) : (b) ); // after this, c = a = 7
On top of this, macros do not support namespaces, which means that defining macros in your code will limit the client code in what names they can use.
This means that if you define the macro above (for max), you will no longer be able to #include <algorithm> in any of the code below, unless you explicitly write:
#ifdef max
#undef max
#endif
#include <algorithm>
Having macros instead of variables / functions also means that you cannot take their address:
if a macro-as-constant evaluates to a magic number, you cannot pass it by address
for a macro-as-function, you cannot use it as a predicate or take the function's address or treat it as a functor.
Edit: As an example, the correct alternative to the #define max above:
template<typename T>
inline T max(const T& a, const T& b)
{
return a > b ? a : b;
}
This does everything the macro does, with one limitation: if the types of the arguments are different, the template version forces you to be explicit (which actually leads to safer, more explicit code):
int a = 0;
double b = 1.;
max(a, b);
If this max is defined as a macro, the code will compile (with a warning).
If this max is defined as a template function, the compiler will point out the ambiguity, and you have to say either max<int>(a, b) or max<double>(a, b) (and thus explicitly state your intent).
A common trouble is this :
#define DIV(a,b) a / b
printf("25 / (3+2) = %d", DIV(25,3+2));
It will print 10, not 5, because the preprocessor will expand it this way:
printf("25 / (3+2) = %d", 25 / 3 + 2);
This version is safer:
#define DIV(a,b) (a) / (b)
Macros are valuable especially for creating generic code (macro's parameters can be anything), sometimes with parameters.
More, this code is placed (ie. inserted) at the point of the macro is used.
OTOH, similar results may be achived with:
overloaded functions (different parameter types)
templates, in C++ (generic parameter types and values)
inline functions (place code where they are called, instead of jumping to a single-point definition -- however, this is rather a recommandation for the compiler).
edit: as for why the macro are bad:
1) no type-checking of the arguments (they have no type), so can be easily misused
2) sometimes expand into very complex code, that can be difficult to identify and understand in the preprocessed file
3) it is easy to make error-prone code in macros, such like:
#define MULTIPLY(a,b) a*b
and then call
MULTIPLY(2+3,4+5)
that expands in
2+3*4+5 (and not into: (2+3)*(4+5)).
To have the latter, you should define:
#define MULTIPLY(a,b) ((a)*(b))
I don't think that there is anything wrong with using preprocessor definitions or macros as you call them.
They are a (meta) language concept found in c/c++ and like any other tool they can make your life easier if you know what you're doing. The trouble with macros is that they are processed before your c/c++ code and generate new code that can be faulty and cause compiler errors which are all but obvious. On the bright side they can help you keep your code clean and save you a lot of typing if used properly, so it comes down to personal preference.
Macros in C/C++ can serve as an important tool for version control. Same code can be delivered to two clients with a minor configuration of Macros. I use things like
#define IBM_AS_CLIENT
#ifdef IBM_AS_CLIENT
#define SOME_VALUE1 X
#define SOME_VALUE2 Y
#else
#define SOME_VALUE1 P
#define SOME_VALUE2 Q
#endif
This kind of functionality is not so easily possible without macros. Macros are actually a great Software Configuration Management Tool and not just a way to
create shortcuts for reuse of code. Defining functions for the purpose of
reusability in macros can definitely create problems.
Preprocessor macros are not evil when they are used for intended purposes like:
Creating different releases of the same software using #ifdef type of constructs, for example the release of windows for different regions.
For defining code testing related values.
Alternatives-
One can use some sort of configuration files in ini,xml,json format for similar purposes. But using them will have run time effects on code which a preprocessor macro can avoid.
In my experience macros are not ideal for program size and can be difficult to debug. But if used carefully they are fine.
Often a good alternatives are generic functions and/or inline functions.
In embedded programming, for example, #define GLOBAL_CONSTANT 42 is preferred to const int GLOBAL_CONSTANT = 42; for the following reasons:
it does not need place in RAM (which is usually very limited in microcontrollers, and µC applications usually need a large number of global constants)
const needs not only a storage place in the flash, but the compiler generates extra code at the start of the program to copy it.
Against all these advantages of using #define, what are the major advantages of using const?
In a non-µC environment memory is usually not such a big issue, and const is useful because it can be used locally, but what about global constants? Or is the answer just "we should never ever ever use global constants"?
Edit:
The examples might have caused some misunderstanding, so I have to state that they are in C. If the C compiler generated the exact same code for the two, I think that would be an error, not an optimization.
I just extended the question to C++ without thinking much about it, in the hopes of getting new insights, but it was clear to me, that in an object-oriented environment there is very little space for global constants, regardless whether they are macros or consts.
Are you sure your compiler is too dumb to optimize your constant by inserting its value where it is needed instead of putting it into memory? Compilers usually are good in optimizations.
And the main advantage of constants versus macros is that constants have scope. Macros are substituted everywhere with no respect for scope or context. And it leads to really hard to understand compiler error messages.
Also debuggers are not aware of macros.
More can be found here
The answer to your question varies for C and C++.
In C, const int GLOBAL_CONSTANT is not a constant in C, So the primary way to define a true constant in C is by using #define.
In C++, One of the major advantage of using const over #define is that #defines don't respect scopes so there is no way to create a class scoped namespace. While const variables can be scoped in classes.
Apart from that there are other subtle advantages like:
Avoiding Weird magical numbers during compilation errors:
If you are using #define those are replaced by the pre-processor at time of precompilation So if you receive an error during compilation, it will be confusing because the error message wont refer the macro name but the value and it will appear a sudden value, and one would waste lot of time tracking it down in code.
Ease of Debugging:
Also for same reasons mentioned in #2, while debugging #define would provide no help really.
Another reason that hasn't been mentioned yet is that const variables allow the compiler to perform explicit type-checking, but macros do not. Using const can help prevent subtle data-dependent errors that are often difficult to debug.
I think the main advantage is that you can change the constant without having to recompile everything that uses it.
Since a macro change will effectively modify the contents of the file that use the macro, recompilation is necessary.
In C the const qualifier does not define a constant but instead a read-only object:
#define A 42 // A is a constant
const int a = 42; // a is not constant
A const object cannot be used where a real constant is required, for example:
static int bla1 = A; // OK, A is a constant
static int bla2 = a; // compile error, a is not a constant
Note that this is different in C++ where the const really qualifies an object as a constant.
The only problems you list with const sum up as "I've got the most incompetent compiler I can possibly imagine". The problems with #define, however, are universal- for example, no scoping.
There's no reason to use #define instead of a const int in C++. Any decent C++ compiler will substitute the constant value from a const int in the same way it does for a #define where it is possible to do so. Both take approximately the same amount of flash when used the same way.
Using a const does allow you to take the address of the value (where a macro does not). At that point, the behavior obviously diverges from the behavior of a Macro. The const now needs a space in the program in both flash and in RAM to live so that it can have an address. But this is really what you want.
The overhead here is typically going to be an extra 8 bytes, which is tiny compared to the size of most programs. Before you get to this level of optimization, make sure you have exhausted all other options like compiler flags. Using the compiler to carefully optimize for size and not using things like templates in C++ will save you a lot more than 8 bytes.