- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Use Static Variables in Arduino?
A static variable is a special kind of variable; it is allocated memory 'statically'. Its lifetime is the entire run of the program. It is specific to a function, i.e., only the function that defined it can access it. However, it doesn't get destroyed after the function call ends. It preserves its value between successive function calls. It is created and initialized the first time a function is called. In the next function call, it is not created again. It just exists.
Example
Take a look at the following example.
void setup() { Serial.begin(9600); Serial.println(); } void loop() { staticFunctionDemo(); } void staticFunctionDemo() { static int staticVariable = 0; int normalVariable = 0; staticVariable = staticVariable+1; normalVariable = normalVariable+1; Serial.print("The value of static variable is: ");Serial.println(staticVariable); Serial.print("The value of normal variable is: ");Serial.println(normalVariable); }
Output
The Serial Monitor output is shown below −
As you can see, the normal variable is created and destroyed with each function call, whereas the static variable preserves its value in between function calls.
- Related Articles
- How to Use Volatile Variables in Arduino?
- How to use Static Variables in JavaScript?
- Where and how to use to static variables in android studio?
- Where and how to use static variables in Android using Kotlin?
- How to Use isControl() in Arduino?
- How to Use isGraph() in Arduino?
- Static Variables in C
- Static variables in Java
- How to use F() macro in Arduino?
- How to Use Word() Function in Arduino?
- Final static variables in Java
- Static and non static blank final variables in Java
- How static variables in member functions work in C++?
- Assigning values to static final variables in java
- Class and Static Variables in C#

Advertisements