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 (eg 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 eg 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. ;-)
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.
您可以将映射到T_Type的方法/函数指针保存在某个地方,但是,是的,这仅仅是出于问题的解决,因此不值得首先创建-硬编码逻辑只能与硬编码值一起使用。
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.