#define or const
>I was thinking about this, and about how solid the C++ specification usually is, so I looked it up. Straight out of MSDN:
>"A pointer to a variable declared as const can be assigned only to a pointer that is also declared as const."
>So you can''t actually do what you stated above
>Not in Visual Studio anyway, it might not be in the C++ standard, though I suspect it is.
ANSI C99 Standard, Sec. 6.7.3:
If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
So, in other words:
const int i = 5;
int *p;
p = &i
*p = 4; //undefined behavior
I think the best reason to use const instead of define is that const obeys the scope rules.
for example, if you had in some header file:
then in another file you have
It would work fine unless you included the file with the #defined UP etc. Once you''ve done that the compiler would see:
enum Dir{1, 2, 3, 4};
Which would cause a compile error. It''s even worse if you included the file the .cpp for the class and not the .h, you get all kinds of strange errors. It''ll probably be even more confusing if you don''t included the file with the #defines in from the start, cos it''ll work until once of the files pull that macro in.
This kind of thing has happened to me a few times because of other people adding #defines to a header file I was using which then breaks my enums, functions or variables. You should try to use const instead of #define as much as possible.
Other than #ifdef, etc. it''s not that often that you need to use #define. ''inline'' and ''const'' are much better (and safer)
for example, if you had in some header file:
#define UP 1#define DOWN 2//etc...
then in another file you have
class Shuttle{ enum Dir {UP, DOWN, LEFT, RIGHT}; //rest of class};
It would work fine unless you included the file with the #defined UP etc. Once you''ve done that the compiler would see:
enum Dir{1, 2, 3, 4};
Which would cause a compile error. It''s even worse if you included the file the .cpp for the class and not the .h, you get all kinds of strange errors. It''ll probably be even more confusing if you don''t included the file with the #defines in from the start, cos it''ll work until once of the files pull that macro in.
This kind of thing has happened to me a few times because of other people adding #defines to a header file I was using which then breaks my enums, functions or variables. You should try to use const instead of #define as much as possible.
Other than #ifdef, etc. it''s not that often that you need to use #define. ''inline'' and ''const'' are much better (and safer)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement