Using pointers to access previously sheltered variables

cat-town
Dan Buch 13 years ago
parent c8233ae231
commit 22c3d73692

@ -13,12 +13,29 @@ int get_age()
} }
int *get_age_pointer()
{
return &THE_AGE;
}
void set_age(int age) void set_age(int age)
{ {
THE_AGE = 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) double update_ratio(double new_ratio)
{ {
static double ratio = 1.0; static double ratio = 1.0;

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

@ -31,6 +31,13 @@ int main(int argc, char *argv[])
log_info("My age is now: %d", get_age()); 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 // test out THE_SIZE extern
log_info("THE_SIZE is: %d", THE_SIZE); log_info("THE_SIZE is: %d", THE_SIZE);
print_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 again: %f", update_ratio(10.0));
log_info("Ratio once more: %f", update_ratio(300.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 // test the scope demo
int count = 4; int count = 4;
scope_demo(count); scope_demo(count);

Loading…
Cancel
Save