Reputation: 121
I have just been using the #define to change my values ex:
#include <iostream>
#include <string>
#define Changed_num 100
using namespace std;
int main ()
{
cout<< Changed_num<< endl;
}
But i heard there's a better way to do that without #define ( what's the other way?)
so i leave me to ask, why would you need #define then? what's the most common use for it?
Upvotes: 1
Views: 625
Reputation: 5102
In general: yes you should try to avoid #define
(see C++ FAQ: Are you saying that the preprocessor is evil? )
The reason is that #define
s are handled by the preprocessor, this is at the lexical level (globally), so the control you have on the effect your #define
replacements is not so good and it is likely to backfire (e.g. substitutions brought in because you included a header that included a header that included a header with a #define
that causes your code to misbehave or simply not to compile).
What you should use?
const int Changed_num=100
) either variables or static class attributes. (see: Why would I use a const variable / const identifier as opposed to #define? ). Check also the constexpr new keyword in C++11.When you should still use #define
Upvotes: 2
Reputation: 1174
For constants values, using const int Changed_num = 100;
has the advantage over #define Changed_num 100
in that you can assign a type. For example, you can const unsigned long Changed_num = 100
, which is a bit tricky to declare as a #define
. (You can do something like #define Changed_num 100ul
, but it's not as obvious.)
One possible use for #define
as part of logging macros, such as boost::log
. They have the advantage of being to interpolate things like __FILE__
and __LINE__
at the point they're called. They are also used for code generation, such as with boost::foreach
(which has been supplanted by the range-based for in c++11
) or boost::python
. In general, however, you're better off using [templated] functions so that you get proper type safety.
The main disadvantage of #define
is that it's a super heavy hammer. If you #define
something, you can't override it later with a local variable or function. One particularly egregious case is Windows.h
which #define
s min
and max
, giving compiler errors if you try to use std:::min
unless you set NOMINMAX
.
Upvotes: 1
Reputation: 41958
The C++ equivalent of #define
in the shown scenario is const
. Internally #define
is used not by the compiler but the precompiler, to modify code before it is actually sent to the compiler. Hence in your case the compiler actually only ever gets to see cout<<100<<endl;
. Using const
is better practice because it is actually type safe.
The most common use case for #define
in C++ is for include guards, to ensure header files are only included once for any specific object.
Runner-up is most likely for platform-specific compilation/optimization, see this link for some examples.
Upvotes: 3