From f2110a5d13f4f1819b7755d0ee79dd63d361f35c Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Tue, 1 Nov 2011 21:56:34 -0400 Subject: [PATCH] Working version of ex22 --- Makefile | 9 +++++++-- ex22.c | 35 +++++++++++++++++++++++++++++++++ ex22.h | 2 +- ex22_main.c | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 99 insertions(+), 3 deletions(-) create mode 100644 ex22.c create mode 100644 ex22_main.c diff --git a/Makefile b/Makefile index 8297ae6..e690e0e 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,17 @@ CFLAGS=-Wall -g -DNDEBUG -EXERCISES = $(patsubst %.c,%,$(shell ls ex*.c | grep -v ex19)) +EXERCISES = $(patsubst %.c,%,$(shell ls ex*.c | egrep -v "ex(19|22)")) -all: $(EXERCISES) +all: $(EXERCISES) ex22_main $(MAKE) -f ex19.mk +ex22_main: ex22.c ex22_main.c ex22.h + $(CC) $(CFLAGS) -c -o ex22.o ex22.c + $(CC) $(CFLAGS) ex22_main.c ex22.o -o $@ + + test: all $(MAKE) -f ex19.mk test diff --git a/ex22.c b/ex22.c new file mode 100644 index 0000000..922ec89 --- /dev/null +++ b/ex22.c @@ -0,0 +1,35 @@ +#include +#include "ex22.h" +#include "dbg.h" + +int THE_SIZE = 1000; + +static int THE_AGE = 37; + + +int get_age() +{ + return THE_AGE; +} + + +void set_age(int age) +{ + THE_AGE = age; +} + + +double update_ratio(double new_ratio) +{ + static double ratio = 1.0; + + double old_ratio = ratio; + ratio = new_ratio; + + return old_ratio; +} + +void print_size() +{ + log_info("I think size is: %d", THE_SIZE); +} diff --git a/ex22.h b/ex22.h index bc894b0..01b93ff 100644 --- a/ex22.h +++ b/ex22.h @@ -2,7 +2,7 @@ #define _ex22_h // makes THE_SIZE in ex22.c available to other .c files -extern int THE_SIZE; +int THE_SIZE; // gets and sets an internal static variable in ex22.c int get_age(); diff --git a/ex22_main.c b/ex22_main.c new file mode 100644 index 0000000..39502e5 --- /dev/null +++ b/ex22_main.c @@ -0,0 +1,56 @@ +#include "ex22.h" +#include "dbg.h" + +const char *MY_NAME = "Zed A. Shaw"; + + +void scope_demo(int count) +{ + log_info("count is: %d", count); + + if(count > 10) { + int count = 100; // BAD! BUGS! + + log_info("count in this scope is %d", count); + } + + log_info("count is at exit: %d", count); + + count = 3000; + + log_info("count after assign: %d", count); +} + + +int main(int argc, char *argv[]) +{ + // test out THE_AGE accessors + log_info("My name: %s, age: %d", MY_NAME, get_age()); + + set_age(100); + + log_info("My age is now: %d", get_age()); + + // test out THE_SIZE extern + log_info("THE_SIZE is: %d", THE_SIZE); + print_size(); + + THE_SIZE = 9; + + log_info("THE_SIZE is now: %d", THE_SIZE); + print_size(); + + // test the ratio function static + log_info("Ratio at first: %f", update_ratio(2.0)); + log_info("Ratio again: %f", update_ratio(10.0)); + log_info("Ratio once more: %f", update_ratio(300.0)); + + // test the scope demo + int count = 4; + scope_demo(count); + scope_demo(count * 20); + + log_info("count after calling scope_demo: %d", count); + + return 0; +}