Demo on the uses of the static reserved word
This commit is contained in:
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
gcc main.c number.c -I. -std=gnu99 -o a.out
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/*
|
||||||
|
*
|
||||||
|
* Demonstration of static variables (External and internal) and functions.
|
||||||
|
*
|
||||||
|
* Author: Kun Deng
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
#include <number.h>
|
||||||
|
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#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;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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);
|
||||||
Reference in New Issue
Block a user