A
Ark
Recently there was a thread (and I believe more than one) on a theme
that a variable, say,
T foo;
is computed once and then is not modified (in the first place,
inadvertently) ever again.
The consensus was that this can only be achieved with
static T foo;
and an API-level function,
T get_foo(void) { return foo;}
or
const T *get_foop(void) {return &foo;}
[There was also an improvement to ensure foo is computed before use.]
However, I see no wrong in giving foo external linkage along with hiding
it. That is, I think the following (in an appropriate header) does the
trick:
extern T foo;
#define foo ((const T)foo)
/*the standard guarantees no recursive expansion */
When my code uses foo, it's the macro and the expression is not an
lvalue. This of course doesn't protect from malicious intent but on the
source code level it's seldom a goal.
Questions:
1. Am I missing something?
2. If not: The look of the code is pretty ugly (T appears twice and foo,
three times; there are two statements for semantically one definition).
I failed to concoct anything more elegant because I don't know of any
way to macroize a macro definition. Does anyone have a better suggestion?
Thank you,
- Ark
that a variable, say,
T foo;
is computed once and then is not modified (in the first place,
inadvertently) ever again.
The consensus was that this can only be achieved with
static T foo;
and an API-level function,
T get_foo(void) { return foo;}
or
const T *get_foop(void) {return &foo;}
[There was also an improvement to ensure foo is computed before use.]
However, I see no wrong in giving foo external linkage along with hiding
it. That is, I think the following (in an appropriate header) does the
trick:
extern T foo;
#define foo ((const T)foo)
/*the standard guarantees no recursive expansion */
When my code uses foo, it's the macro and the expression is not an
lvalue. This of course doesn't protect from malicious intent but on the
source code level it's seldom a goal.
Questions:
1. Am I missing something?
2. If not: The look of the code is pretty ugly (T appears twice and foo,
three times; there are two statements for semantically one definition).
I failed to concoct anything more elegant because I don't know of any
way to macroize a macro definition. Does anyone have a better suggestion?
Thank you,
- Ark