-4

Possible Duplicate:
“static const” vs “#define” in C

My first thought is that this is implied, but is there ever a reason why you would use const instead of #define?

If you set a global variable, why would you ever want to change it, and wouldn't you want to protect it globally as well?

Community
  • 1
  • 1
frankV
  • 5,353
  • 8
  • 33
  • 46

3 Answers3

5

Const usually replaces #define

#define is a pre-processor macro that can do textual replacement. You can use it to define a constant or a macro or do all sorts of other things.

const is a type-safe way to define a compile-time constant

These two mechanisms occur at different times in the compilation process, but in general, const was created to rectify the problems of #define.

I've rarely seen people do something like

#define CONSTINT  const int

but it is legal.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
gbronner
  • 1,907
  • 24
  • 39
4

const is only relevant for variables that are passed around at runtime that ensures that subroutines cannot change them. #define is a preprocessor compiletime directive that replaces whatever you define with what you have defined it as. Therefore, they are for different purposes.

Steztric
  • 2,832
  • 2
  • 24
  • 43
2

Edit this is an answer to your original question, of whether you'd use const with a define ... it doesn't really make sense now you've edited the question to ask something different.

A #define does not define a variable, so you can't change it anyway, so the question doesn't make sense.

This isn't even possible:

#define FOO 99

int main()
{
    FOO = 98;
}

Because the preprocessor substitutes the macro FOO for the replacement 99, so the compiler sees this code:

int main()
{
    99 = 98;
}

And obviously that's nonsense. You can't assign to a literal, it's not a variable (const or not) it's just a value.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521