0

Possible Duplicate:
Should I use #define, enum or const?

Recently I've found it convenient to use using enumeration values to define constants but I'm interested to know what are the pros and cons of using const ints, #defines vs enumeration values for constants?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

2

I believe using #define for constants is a relic of C, because in C there was not always a const keyword. Now you can use const int instead, and should. As for enum, C++11 provides some neat features with enum that are worth checking out, and they will probably suit your needs better than anything if you are going to have multiple constants that are somehow related.

Eric B
  • 4,367
  • 5
  • 33
  • 43
  • 1
    There *is* a `const` keyword in C. It's just less useful because when C says it requires a "constant expression", it means a literal, not a `const`. –  Nov 21 '12 at 16:02
  • 1
    I don't think the const keyword has always been there though. It was introduced later on, after the introduction of C++ – Eric B Nov 21 '12 at 16:03
  • It was definitely [present in C89/ANSI C](http://en.wikipedia.org/wiki/C_%28programming_language%29#Keywords). That's after Bjarne started working on what would become C++, and (according to Wikipedia) even a few years after they started calling it C++. But I doubt C started adopting C++ features that early (it took them until 1990 to put `//` comments into the standard, and that's a really simple feature compared to `const`). It appears K&R didn't have `const`. But I failed to find a source, both for it originating in C and for it coming from C++. –  Nov 21 '12 at 16:12
  • Also, constants are numbers, and enums have (some kind of) a type in C++03 and can have a strong type in C++11. So different solutions suit different problems. – juanchopanza Nov 21 '12 at 16:13
  • Nevermind, you are right. C++ introduced `const` (in 1981 or earlier) as described by [Sibling Rivalry: C and C, Bjarne Stroustrup](http://www.stroustrup.com/sibling_rivalry.pdf) (page 5) –  Nov 21 '12 at 16:19