Reputation: 1228
If I have the code below:
#define POUND_PER_DOLLAR 73
int nPound = 4 * POUND_PER_DOLLAR;
AND
int POUND_PER_DOLLAR = 122;
int nPound = 4 * POUND_PER_DOLLAR;
Are there instances where usage of one is more suited than the other?
Upvotes: 1
Views: 91
Reputation: 1980
#define identifier replacement
When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code by replacement. This replacement can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++ proper, it simply replaces any occurrence of identifier by replacement.
Disadvantages of using #define: method,
Upvotes: 2
Reputation: 63124
Neither. The #define
is not type-safe, the int
is non-const. This is the constant you're looking for :
int const POUND_PER_DOLLAR = 122;
Upvotes: 3
Reputation: 477020
If you need the address, you need a variable:
void foo(int *);
foo(&POUND_PER_DOLLAR); // must be an lvalue
If you need a constant expression, a macro (or at least a constant) will work:
char array[POUND_PER_DOLLAR]; // must be a constant expression
However, the most appropriate construction is probably a constant:
const int kPoundPerDollar = 73;
int nPound = 4 * kPoundPerDollar;
void bar(const int *);
bar(&kPoundPerDollar); // works
char c[kPoundPerDollar]; // also works
template <const int * P> struct X {};
X<&kPoundPerDollar> x; // also works
Upvotes: 3