Reputation: 70263
It is common practice to define symbolic constants in a header file:
#define T_FOO 1
#define T_BAR 2
Ugly.
static const int T_FOO = 1;
static const int T_BAR = 2;
Better, since not preprocessor.
enum
{
T_FOO = 1,
T_BAR
} T_Type;
Better still, since T_Type
carries information of purpose, and the compiler can do additional checks (e.g. if all cases are handled in a switch
).
There's probably half a dozen more variants. One thing though... they all disclose numerical values to the client. I'd like to keep those values hidden, simply because they shouldn't matter. But the one way I could think of...
typedef int T_Type;
// defined elsewhere
extern const T_Type T_FOO;
extern const T_Type T_BAR;
...does not work for e.g. case
statements (as T_FOO
and T_BAR
are constants, but not a compile-time constant expressions).
Is there a way to have it all?
switch
statements?My level of understanding says "no", but I know that I don't know everything. ;-)
Upvotes: 1
Views: 457
Reputation: 7118
Your typedef declaration was wrong. What about this one?
typedef int T_Type;
// defined elsewhere
extern const T_Type T_FOO;
extern const T_Type T_BAR;
// elsewhere defined as, say
const T_Type T_FOO = 1;
const T_Type T_BAR = 2;
Upvotes: 0
Reputation: 138
You can hold method/function pointers mapped to T_Type somewhere, but yep, it's all just hacks out of problem which don't worth to be created in first place - hardcoded logic can only work with hardcoded values.
Upvotes: 0
Reputation: 145249
To be usable in as switch
statement labels the values have to be seen by the compiler earlier in the source of this translation unit.
So essentially, no, you can't declare symbolic constants without disclosing their values, and use them as labels in a switch
.
However, you can use an if
-else
construction.
Upvotes: 2