From 47e0041c8696b3e731c5452f76bd956529773927 Mon Sep 17 00:00:00 2001 From: kdeng00 Date: Wed, 4 Nov 2020 21:20:39 -0500 Subject: [PATCH] Demo on the uses of the static reserved word --- ch_04/static_demo/compile.sh | 5 ++++ ch_04/static_demo/main.c | 25 ++++++++++++++++++++ ch_04/static_demo/number.c | 44 ++++++++++++++++++++++++++++++++++++ ch_04/static_demo/number.h | 12 ++++++++++ 4 files changed, 86 insertions(+) create mode 100755 ch_04/static_demo/compile.sh create mode 100644 ch_04/static_demo/main.c create mode 100644 ch_04/static_demo/number.c create mode 100644 ch_04/static_demo/number.h diff --git a/ch_04/static_demo/compile.sh b/ch_04/static_demo/compile.sh new file mode 100755 index 0000000..e76077d --- /dev/null +++ b/ch_04/static_demo/compile.sh @@ -0,0 +1,5 @@ +#!/bin/bash + + + +gcc main.c number.c -I. -std=gnu99 -o a.out diff --git a/ch_04/static_demo/main.c b/ch_04/static_demo/main.c new file mode 100644 index 0000000..5392956 --- /dev/null +++ b/ch_04/static_demo/main.c @@ -0,0 +1,25 @@ +/* + * + * Demonstration of static variables (External and internal) and functions. + * + * Author: Kun Deng + */ + +#include + +#include + + +int main() +{ + const int number_limit = 10; + printf("Printing %d numbers\n", number_limit); + + for (int i = 0; i != number_limit; ++i) + { + printf("%d: %d\n", i, Number_get_number()); + } + + + return 0; +} diff --git a/ch_04/static_demo/number.c b/ch_04/static_demo/number.c new file mode 100644 index 0000000..a87ce70 --- /dev/null +++ b/ch_04/static_demo/number.c @@ -0,0 +1,44 @@ +#include + +#include "number.h" + +/* Variable will only be accessible from this file because + * it's static + */ +static int number = 1; + + +static void do_something() +{ + /* Retains the value outside of the scope + * because it's an internal static variable. + */ + static int changer = 1; + + number += changer; + + if (changer % 10 >= 4) + { + changer += 5; + } + else if (changer % 10 < 4) + { + changer += 3; + } + else + { + changer *= 2; + } +} + + + +int Number_get_number() +{ + extern int number; + + do_something(); + + return number; +} + diff --git a/ch_04/static_demo/number.h b/ch_04/static_demo/number.h new file mode 100644 index 0000000..b82bbbf --- /dev/null +++ b/ch_04/static_demo/number.h @@ -0,0 +1,12 @@ + + +/* Does something to a number. This function is static and + * will not be accessible outside of this file. Functions and + * variables defined as static are not visible to outside + * files. This function is private to this file and can only + * be called from within. + */ +static void do_something(void); + + +int Number_get_number(void);