Using pointers to access previously sheltered variables

This commit is contained in:
Dan Buch 2011-11-04 08:43:16 -04:00
parent c8233ae231
commit 22c3d73692
3 changed files with 35 additions and 0 deletions

17
ex22.c
View File

@ -13,12 +13,29 @@ int get_age()
}
int *get_age_pointer()
{
return &THE_AGE;
}
void set_age(int age)
{
THE_AGE = age;
}
double *get_function_static(double to_add)
{
static double value = 1.0;
double old = value;
value = value + to_add;
return &value;
}
double update_ratio(double new_ratio)
{
static double ratio = 1.0;

2
ex22.h
View File

@ -6,6 +6,8 @@ int THE_SIZE;
// gets and sets an internal static variable in ex22.c
int get_age();
int * get_age_pointer();
double * get_function_static(double);
void set_age(int age);
// updates a static variable that's inside update_ratio

View File

@ -31,6 +31,13 @@ int main(int argc, char *argv[])
log_info("My age is now: %d", get_age());
int new_age = 44;
log_info("Setting age directly to %d", new_age);
int *age = get_age_pointer();
*age = new_age;
log_info("My age is now: %d", get_age());
// test out THE_SIZE extern
log_info("THE_SIZE is: %d", THE_SIZE);
print_size();
@ -45,6 +52,15 @@ int main(int argc, char *argv[])
log_info("Ratio again: %f", update_ratio(10.0));
log_info("Ratio once more: %f", update_ratio(300.0));
// accessing a function static
double *func_static_value = get_function_static(4.0);
log_info("get_function_static(4.0) = %.1f", *func_static_value);
double new_func_static_value = 8.0;
log_info("Setting the function static var directly to %.1f",
new_func_static_value);
*func_static_value = new_func_static_value;
log_info("get_function_static(4.0) = %.1f", *get_function_static(4.0));
// test the scope demo
int count = 4;
scope_demo(count);