referencing a global variable from a function without passing it asan argument

I

iC and iC++

I have the following code snippet from my program that i am working on

int running = 0;
float var1, average_value;

void is_process_running(void) {
if (fabs(var1 - average_value) <= 0.001)
{
*(&running) = 0;
}
else
*(&running) = 1;
}

var1 and average value get their value from somewhere else.

is it possible to change the value of "is_running" by referencing to
it with a pointer to its address i.e. <return *(&running)> with out
passing it as an argument to the function or making it the return
value of the function.

Thanks,
 
K

Keith Thompson

iC and iC++ said:
I have the following code snippet from my program that i am working on

int running = 0;
float var1, average_value;

void is_process_running(void) {
if (fabs(var1 - average_value) <= 0.001)
{
*(&running) = 0;

This is equivalent to
running = 0;
Why not just write that?
}
else
*(&running) = 1;

And this is equivalent to
running = 1;
var1 and average value get their value from somewhere else.

is it possible to change the value of "is_running" by referencing to
it with a pointer to its address i.e. <return *(&running)> with out
passing it as an argument to the function or making it the return
value of the function.

Assuming that you mean "running" rather than "is_running", yes, of
course it's possible; that's what your code snippet does. (But it's a
pointer to the object, not "a pointer to its address". A pointer value
*is* an address.)

Excessive use of globals variables is a bad idea. Without commenting on
the references to var1 and average_value, your is_process_running()
function should probably just return a value indicating whether the
process is running or not (that's certainly what I'd expect given the
name). For example:

int is_process_running(void) {
return fabs(var1 - average_value) > 0.001;
}
 
I

iC and iC++

    int is_process_running(void) {
        return fabs(var1 - average_value) > 0.001;
    }

Thanks a lot. This is great. I am trying to limit the use of global
variables as much as I can.
 
B

Barry Schwarz

Thanks a lot. This is great. I am trying to limit the use of global
variables as much as I can.

Then the values to be processed by the function should be passed as
arguments rather than store them in global variables referenced by the
function directly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top