aboutsummaryrefslogtreecommitdiffstats
path: root/source/lang/static.rst
diff options
context:
space:
mode:
authorMarti Bolivar <mbolivar@mit.edu>2010-11-28 11:23:33 -0500
committerMarti Bolivar <mbolivar@mit.edu>2010-11-28 11:23:33 -0500
commitd9cbd78e29d42e70bb46641dd43ee0772c8c975f (patch)
tree80a67cba4468dbcd89b3cd23ad56695b1f146c66 /source/lang/static.rst
parent546b34076d230b617ba86defb6b90cd934b01878 (diff)
downloadlibrambutan-d9cbd78e29d42e70bb46641dd43ee0772c8c975f.tar.gz
librambutan-d9cbd78e29d42e70bb46641dd43ee0772c8c975f.zip
reorganized all the arduino/ docs into a lang/ subdirectory since
they're properly CC attributed now.
Diffstat (limited to 'source/lang/static.rst')
-rw-r--r--source/lang/static.rst57
1 files changed, 57 insertions, 0 deletions
diff --git a/source/lang/static.rst b/source/lang/static.rst
new file mode 100644
index 0000000..4646db1
--- /dev/null
+++ b/source/lang/static.rst
@@ -0,0 +1,57 @@
+.. highlight:: cpp
+
+.. _lang-static:
+
+Static
+======
+
+The ``static`` keyword can be used to create variables that are
+visible to only one function. However, unlike local variables that get
+created and destroyed every time a function is called, ``static``
+variables persist beyond the function call, preserving their data
+between function calls.
+
+Variables declared as ``static`` will only be created and initialized
+the first time a function is called.
+
+.. note:: This is only one use of the ``static`` keyword in C++. It
+ has some other important uses that are not documented here; consult
+ a reliable C++ reference for details.
+
+Example
+-------
+
+One use case for ``static`` variables is implementing counters that
+last longer than the functions which need them, but shouldn't be
+shared to other functions. Here's an example::
+
+ void setup() {
+ SerialUSB.begin();
+ }
+
+ void loop() {
+ int reading;
+ if (timeToReadSensors()) {
+ reading = readSensors();
+ }
+ // do something with reading
+ }
+
+ int readSensors() {
+ static int numSensorReadings = 0;
+ numSensorReadings++;
+ if (numSensorReadings % 100 == 0) {
+ SerialUSB.print("just got to another 100 sensor readings");
+ }
+ return analogRead(...);
+ }
+
+In this example, the static variable ``numSensorReadings`` is
+initialized to zero the first time ``readSensors()`` is called, and
+then incremented, so it starts out at one. Subsequent calls to
+``readSensors()`` won't reset ``numSensorReadings`` to zero, because
+it was declared ``static``. Thus, ``numSensorReadings`` is a count of
+the number of times that ``readSensors()`` has been called.
+
+
+.. include:: cc-attribution.txt