1

I would like to understand the difference between defining a constant variable as follows:

const int ONE = 1; 

and using a preprocessor directive:

#define ONE (1)

I know that in the second case "1" gets in some sense hardcoded and the compiler does not even see the variable ONE, but I am not sure about the first case. The fact of declaring the variable as constant just prevents from accidentally change its value, or does the compiler catch the opportunity to do some optimization? Is there any significant benefit of one approach over the other?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
undy
  • 93
  • 7
  • 1
    @AlokSave: That question is about C++ – sth Apr 12 '14 at 14:42
  • This http://stackoverflow.com/a/1674118/1809377 and this http://stackoverflow.com/a/1674459/1809377 answer your question definitively. – ajay Apr 12 '14 at 14:45

1 Answers1

0

In C, const int c; means that c can't be modified during the run of program. However, c is not a constant during compile time and can not be used in constant expressions. So for example the program:

const int MAX = 10;
int a[MAX];

does not compile, while:

#define MAX 10
int a[MAX];

does.

In C++, const variables are true compile-time constants, so there may be less reasons to use #define for it. An example where #define is necessary is when you need to use the constant in an #if directive.

Marian
  • 7,402
  • 2
  • 22
  • 34
  • what about variable-length arrays? `int a[MAX];` would compile just fine. – ajay Apr 12 '14 at 14:40
  • Of course, variable length arrays are called variable length because they do not require constant expression as dimension. They can be used for local variables only. – Marian Apr 12 '14 at 14:44