Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Preventing modifications to global variable

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hello,

I am working on a system where I need to provide access to a variable defined in one module to several other modules. However, these modules should only be able to see the value of the variable whereas the module in which it is defined needs to be able to modify it. Due to performance considerations, a wrapper function that returns the value of the variable is not an option - this variable needs to be queried millions of times. Does anyone have any ideas how to do this? Is there any smart way to declare the variable as const and then 'cast away' the const in the module?

Thanks,
SS

Note: This is C-specific and I cannot use C++ to do this.
 
How about this?

have the global var and a const reference to it?


int global = 7;
const int* return_var = &global;

you will just need to deref it but it should do the trick;

Matt
 
Addition to above... the place you want to modify the value, use

global = new_value;

int the other code use *return_var to get the value. Changes to global will be represented with the const pointer.

Matt
 
Here's my input :)

In the module's header file, declare a pointer to the variable type. This will be how the user of the module reads it (but doesn't write it):

/* modify.h */

const int * const you_can_see_me;

So, the user can't modify what the variable points to (through this pointer) OR set the pointer to point to something else.

Then, in your source file, define the actual variable as static so the user can't modify it directly:

/* modify.c */
#include "modify.h"

static int you_cant_see_me;

If it makes sense for your app, you can have routines in modify.c to control when the user of the module can see the value of you_cant_see_me through the pointer in modify.h:

you_can_see_me=NULL; /* user can't see value */

you_can_see_me=&you_cant_see_me; /* user CAN see value */

Of course, none of this is even remotely bulletproof, The user can still cast around the whole affair and modify the value of you_cant_see_me, probably silencing any warnings that might come from the compiler:

int *foo=(int *)you_can_see_me;

*foo=10;

The idea is that it'll keep the users of your module honest, but only if they're honest to begin with :)
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top