Can a const variable which can change be used to declare and define an array in ... C++?
No.
Though it can be successfully compiled
... by a compiler that extends the language. There is no guarantee that it can be compiled by other compilers.
because number1 is non const variable.
Sort of, indirectly. The exact reason is that number1
is not a constant expression. Making the variable const would be sufficient in this case to make the example well-formed because the initialiser of the variable is a constant expression.
Now the number2 is a const variable.
Also compiled successfully.
I feel it is wrong
Your feelings are correct. The program is still ill-formed. As a standard conforming compiler is required to tell you (you can ask GCC to conform to the standard by using the -pedantic
option):
warning: ISO C++ forbids variable length array 'salary' [-Wvla]
double salary[number2];
^~~~~~
Can someone explain why it is wrong ?
It is wrong because the size of the array is not a constant expression, as required by the language.
The identifier of a const variable is not necessarily a constant expression. The variable must be const, and the initialiser of the variable must be a constant expression. 4 is a constant expression. Identifier of a non-const variable is not a constant expression. If the value is determined at runtime, then it cannot be a constant expression.
Can a const variable which can change be used to declare and define an array in C ...?
Potentially, yes. Before C99, no for same reasons as described in the C++ answer.
In C99, yes because variable length arrays were introduced to the language. Since C11, yes if the compiler supports it; VLA were made optional in this standard.