I have some constant values and arrays defining their labels and their hash codes. For example,
#define LABEL_A 0 //or const int LABEL_A = 0;
#define LABEL_B 1
#define LABEL_C 2
#define LABEL_D 3
const char *VALUE[] = {"LABEL_A", "LABEL_B", "LABEL_C", "LABEL_D"};
const int VALUE_HASH[] = {67490, 67491, 67493, 67459);
At run-time, these labels can come in any order and needs to be parsed accordingly. I am using switch case for this purpose. This code is generating error at compile time "constant expression is required.
function(const char* LabelAtRuntime){
int i = getHashCode(LabelAtRuntime);
switch(i){
case VALUE_HASH[LABEL_A]: //line giving compile time error
break;
default:
break;
}
But, when I provide actual constants, it works. This code works well.
function(const char* LabelAtRuntime){
int i = getHashCode(LabelAtRuntime);
switch(i){
case 67490: //line not giving compile time error
break;
default:
break;
}
- I am unable to understand, why is it happening? Both my array and its index are constants, then isn't it equivalent to a constant literal?
- Is there any other way by which I can provide my constants in required manner?
I am using constants in this manner to provide better code semantics, readability and reusability. Please do not provide if-else
based solution. In above example, there are only 4 labels, but in practical, there could be 100.