How to "#define" struct field or struct name
I want to do something like:
int desc = -1;
if ( DB_DBM_HSEARCH == 1 ) { desc = db->fd } else desc = db开发者_开发问答->dbm_pagf;
This is impossible because of a compiler error.
Is it possible to do something like:
#define DESC db->fd //and then
int desc = DESC;
?
Sure. Though I think this would be a more suitable way to do it using macro functions (so you can change your variable names if you need to). Assuming DB_DBM_HSEARCH
is a macro:
/* conditionally define the macros */
#if DB_DBM_HSEARCH == 1
# define DESC(db) (db)->fd
#else
# define DESC(db) (db)->dbm_pagf
#endif
/* then to initialize */
int desc = DESC(db);
You can, but don't use macros for this sort of thing, just use nicely named variables.
精彩评论