mohi a écrit :
Alexander Dong Back Kim wrote:
I know 'const' means there is no affects on member variables or
original variables. However, we can control it on codes right? then
why should we have to use the keyword?
In some cases it's mandatory. For example:
const int size = 10;
int table[size]; // 'size' must be const
In other cases it's a good safeguard against some programming errors
(if you accidentally try to modify a const variable, the error will be
detected at compile time).
i would like to add to the above post that if iam not wrong
its not neccessary to declare "size" in the present example as const,
this syntax was required in i guess old compilers but for new
compilers declaring
int size=10;
int array[size];
is absolutely fine
though its a good practice to declare size here as "const int"
You are wrong from the standard point of view. This syntax is supported
because c++ compilers also implement C standard which authorize this.
From 8.4.4 of the standard, arrays are defined as:
T D where D has the form D1 [constant-expression]
So the size must be constant value.
If you compile with -pedantic, g++ 3.4.5 gives
error: ISO C++ forbids variable-size array `table'
Note also that the following is always an error:
int size = 10;
int table[size]={}
While the following works:
const int size = 10;
int table[size]={}
Michael