using #define over const?

i find #define simple and more organized to declare my constants, but what advantages does const have over #define if any?
#define is awful for constants. Just a few reasons why it should be avoided:


1) #define ignores all language and scope rules, greatly polluting the global namespace... often resulting in very bizarre error messages or even worse, runtime bugs. Sometimes those which can't even be avoided.

Example:
1
2
3
4
5
6
7
8
9
// in your header
#define foo 10

// in the header of some library you're using
void somefunc()
{
  int foo = 5;  // error, "int 10 = 5;" makes no sense
  //..
}

Anything you #define has a risk of colliding with everything that gets #included or declared after it. Throw all class/namespace/scope rules out the window.

2) #define'd constants are not recognized by a debugger

3) You cannot get a pointer to a #define'd constant

4) #define does not give you any extra performance gain over the much safer alternatives.

5) #define'd values are context dependent... so if you forget to wrap your #define in parenthesis you might shoot yourself in the foot.

Example:

1
2
3
4
#define foo 5
#define bar foo+3  // <- BAD BAD BAD

int baz = bar*10;  // expect 80, but really get 35 
Last edited on
That was an eye opener, really appreciate the input on this subject. Ill be sure to use const instead now.
Topic archived. No new replies allowed.