Data Storage

In Arduino C++ do variables lose their stored data at the completion of a sub or function? (little vb6 lingo there) The reason why I ask is because the string is appended and there's no easy way to clear the string at the completion of what is called a Sub or Function in Visual Basic 6.0. In vb6 the variables lose stored data unless they are declared as static.

double getdivisions()


char key = kpd.getKey();

double Degrees = 0;

string divstr;

int divs = 0;



lcd.print("Enter Division:");


lcd.print("OK = # ");



lcd.print(" D");


while(key != '#')


switch (key)


case NO_KEY: break;

case 'D': lcd.setCursor(16,1);

lcd.print(" ");




case '0': divstr += ("0");

case '1': divstr += ("1");

case '2': divstr += ("2");

case '3': divstr += ("3");

case '4': divstr += ("4");

case '5': divstr += ("5");

case '6': divstr += ("6");

case '7': divstr += ("7");

case '8': divstr += ("8");

case '9': divstr += ("9");




key = kpd.getKey();


Degrees = (360/divstr toInt());

return Degrees;


Please learn some C/C++ lingo: it is a function.

It is not "Arduino C++". gcc is used as a compiler and it is a real compiler for C and C++. Arduino adds some libraries and functions to make common issues easier.

The answer to your question is "It depends." C++ allows you to define variables in various places (e.g. globally or local to the function) and with various modifiers (e.g. static) that affect how the variable is handled.

A C string (the lower case 's' is important) is typically an array of char. Putting a zero (or null or other things) into the zeroth position would clear the string if necessary.

"Arduino C++" has the same variable scope and lifetime rules as "real" C++ because it is real C++.

In your example
Degrees will be returned and after that no longer exist.
divstr will be empty when the function is called; it's a new variable. The declaration should be

String divstr;

Note the capital S.

Side notes:
If the character enter is e.g. 4, divstr will contain 456789. This is due to the missing break statements for the cases 0..9.
Stay away from the String class (capital S); it can result in memory fragmentation and as a result of that unexpected behaviour at run time. Learn to use so-called c-strings (NUL terminated character arrays).
Please learn to indent your code properly (use tools -> autoformat in the IDE); it helps you (and us) in following the flow of a program.