5

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

When I do this :

#define WEEKDAYS 7

and that :

const int WEEKDAYS = 7;

Any difference between them ? seems that both do the same thing - sets a constant value for future usage within the code .

Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318
  • 2
    You've tagged this as both C and C++. The answers are somewhat different for the different languages. –  Aug 25 '12 at 16:29
  • It'd be easier to say **NEVER** tag a question both C and C++. – Jeff Mercado Aug 25 '12 at 16:31
  • @JeffMercado It'd be easier, but it'd be wrong. :) The easiest example is a question asking specifically about one of the differences between C and C++ (I recall a recent question asking why `sizeof('a')` differs from `sizeof(char)` in C, but not in C++) –  Aug 25 '12 at 16:33
  • @hvd: What that's a question about specific differences between the two languages. What I really meant was tagging with both tags on a question that's not specifically looking for a comparison of the languages. But whatever, it's still going to happen whether we like it or not. – Jeff Mercado Aug 25 '12 at 16:38
  • Agreed. FWIW, this is now closed as a duplicate of the question for C, but as ron has removed the C tag (thanks), http://stackoverflow.com/questions/1637332/static-const-vs-define (linked in the other question) may be useful to mention here. –  Aug 25 '12 at 16:42

2 Answers2

7
#define WEEKDAYS 7

void f() {
    int WEEKDAYS = 3; // error
}

const int WEEKDAYS_CONST = 7;

void g() {
    int WEEKDAYS_CONST = 3; // okay: local scope for WEEKDAYS_CONST
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
2
#define WEEKDAYS 7

Replaces all occurrence of the word WEEKDAYS in your source file with the digit 7.

const int WEEKDAYS = 7;

Defines an actual constant represented by 7 that you can access in your code.

Qiau
  • 5,976
  • 3
  • 29
  • 40