一. Java
Java use `final` to represent a constant:
- compile-time constant
- value initialized at run-time but not change ever since
data can be:
- primitive -- the data can't be changed
- object reference -- the reference can't change but the object can change
// can also be compile-time constants:
public static final int VALUE_THREE = 39;
// can also be run-time constants:
private final int i4 = rand.nextInt(20);
static final int INT_5 = rand.nextInt(20);
// a final reference
private final String s1 = new String("s1");
二. c++
c++ using the keyword `const` to address this:
- compile-time constant
- value initialized at run-time but not change ever since (see following -- cited from stackoverflow)
|
As a static or function-local variable:
const int x = calcConstant();
As a class member:
struct ConstContainer {
ConstContainer(int x) : x(x) {}
const int x;
};
|
data can be:
- primitive and object -- the data can't be changed
- pointer -- you can choose pointer or the memory it point to
const int *p; // can't change that int
int * const p; // can't change pointer
int const *p; // the same as first
const int * const p; // can't change both
Something else:
If you want to use the a constant array in separated file, you have to add `extern` before it for the const in c++ is default to be internal linkage, ie it is invisible outside of the file.
// a.h: the size have to larger than number of elements in initializing list
extern const int a[size];
// a.cpp: size >= 2
extern const int a[] = {1, 2 };
Reference:
-
Where
to put compile-time-constant arrays?
-
More:
-
Gits:
-
Java
constant – final
-
extern_const.cpp
评论
发表评论