Go Down

Topic: difference between static int and int (Read 3762 times) previous topic - next topic

arslankhan

Jun 06, 2013, 11:45 am Last Edit: Jun 06, 2013, 12:09 pm by arslankhan Reason: 1
I am little bit confused in the follwoing program.
Code: [Select]
void myfunction(){  
int my_stack=0;
static int my_static=0;

Serial.print("my_static=");
Serial.println(my_static);

Serial.print("stack=");
Serial.println(my_stack);
my_stack++;
my_static++;
}

my_static variable, declared as static within a function, retains its value between successive calls to my_function() while my_stack does not.  The output of 5 successive calls to my_function() is
Code: [Select]
my_static=0
stack=0
my_static=1
stack=0
my_static=2
stack=0
my_static=3
stack=0
my_static=4
stack=0


every time when myfunction() runs it comiles static int my_static=0; then how my_static can be increased?

PaulS

Quote
every time when myfunction() runs it comiles static int my_static=0; then how my_static can be increased?

No. When the code runs, nothing is compiled.

When the code is compiled, the compiler notices the static keyword in front of my_static and generates code to initialize the variable ONCE. The compiler notices the lack of the static keyword in front of stack, and generates code to initialize the variable every time.

majenko

#2
Jun 06, 2013, 12:38 pm Last Edit: Jun 06, 2013, 12:42 pm by majenko Reason: 1
When you define a local variable as static and equate it to something you are telling it the starting value only.  This value only gets assigned once.

It is functionally the same as a global variable, except the scope (where you can access it from) is more limited.

The code to assign the value to the static variable is run during the startup phase (not the setup function - before even that runs) - a process called "crt0" for "C RunTime phase 0".  This copies all the values for the pre-set (static and global) variables from flash into RAM, and that is the only time these initialization values are ever assigned.

In effect the "=0" of your static declaration is not performed there, but right at the start of the program before even setup() runs.

econjack

Your definition of my_static tells the compiler several things about the variable:

1. Because it is defined within myfunction(), my_static "lives" and is only visible within the opening and closing braces of myfunction(). That is, my_static has local scope within myfunction().
2. Because your definition of my_static is prefaced with the keyword static, it's as though the compiler removes the line of code that defines my_static out of myfunction() and places it before setup(). This means the definition is only read at program startup. This causes my_static to get a memory address (i.e., an lvalue) where it will "live" for the entire running of the program and initializes its value (i.e., its rvalue) to 0.

Therefore, when the code enters myfunction() the first time, my_static becomes visible (it's in scope). When the statement my_static++ is executed, the compiler fetches the rvalue from memory (i.e., 0) and increments it (rvalue now equals 1). Because you used the static keyword, my_static is not reallocated each time myfunction() is called. When the second call is performed, the same lvalue is used to fetch the rvalue (which is now 1) and it is again incremented (i.e., rvalue =2). This is why static variables "remember" their previous values. In short, your code is doing exactly what a static variable should do: get allocated once before the program starts and never get reallocated again. Because its lvalue is never reassigned, its rvalue is retained between function calls.

arslankhan

Thanks to all specially econjack ..thanks a lot. Well explanation from every one

firashelou

hello guys,
i wanted to open a new topic then i saw this one already opened, so i read what is in this post but i couldn't really understand Static!

can you please explain it a very simple way ?

i understood this but not sure:
static variable should be declared inside a special_function(){}

then i see some examples declared this static at the beginning of the sketch even before void setup()

and this static if at the starts static = 0

the second time the sketch runs it will be incremented to 1 for example if the program says and it will stay 1 until next run time of the sketch

right ?
Aiming for the unreachable !

aarg

i understood this but not sure:
static variable should be declared inside a special_function(){}

Should? I don't see that anywhere. But you can.
  ... with a transistor and a large sum of money to spend ...
Please don't PM me with technical questions. Post them in the forum.

guix

#7
Sep 12, 2015, 07:06 pm Last Edit: Sep 12, 2015, 07:12 pm by guix
Quote
then i see some examples declared this static at the beginning of the sketch even before void setup()
It's only useful when you make a sketch with multiple files and you want global variables of the same name in more than one file. You add the static keyword to limit this variable to the current file.

Say you have in file1.ino
Code: [Select]

int bla = 1;

void setup()
{
   ...
}

void loop()
{
   ...
}


And in file2.cpp you have:
Code: [Select]

int bla = 2;


When you compile you will have an error about multiple definitions of  variable "bla", because both files are merged (basically). So you change file2.cpp to:
Code: [Select]

static int bla = 2;


And there is no more error, because this variable now belong only to file2.cpp.

robtillaart

#8
Sep 12, 2015, 07:25 pm Last Edit: Sep 12, 2015, 07:26 pm by robtillaart
Note that pointer magic can do ... well magic .... like changing a static variable inside a function.

( UNO, IDE 1.5.8 )

Code: (proof of concept) [Select]

void setup()
{
  Serial.begin(115200);
  Serial.print("Start ");
  Serial.println(__FILE__);
}

int* f()
{
  static int p = 0;
  Serial.println(p);
  return &p;
}

void g(int *pp)
{
  *pp = *pp + 1;
}

void loop()
{
  int *a = f();
  g(a);
  delay(1000);
}


warning: don't do this at home ...
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

firashelou

It's only useful when you make a sketch with multiple files and you want global variables of the same name in more than one file. You add the static keyword to limit this variable to the current file.

Say you have in file1.ino
Code: [Select]

int bla = 1;

void setup()
{
   ...
}

void loop()
{
   ...
}


And in file2.cpp you have:
Code: [Select]

int bla = 2;


When you compile you will have an error about multiple definitions of  variable "bla", because both files are merged (basically). So you change file2.cpp to:
Code: [Select]

static int bla = 2;


And there is no more error, because this variable now belong only to file2.cpp.
i don't really get it,
i know from other languages that static or the world specific for that language means this variable can be used inside one function only, global means any functions can use it

i made a little search i found on a forum that they say a static variable means it can be used in 1 function only the one declared in, but can not be used in another unless it's not static

about your example i don't get it ! why is it .cpp and not .ino ?
and why would i have multiple files ?! you mean multiple tabs ?
Aiming for the unreachable !

Vaclav

It is functionally the same as a global variable, except the scope (where you can access it from) is more limited.
When you define a local variable as static and equate it to something you are telling it the starting value only.  This value only gets assigned once.

It is functionally the same as a global variable, except the scope (where you can access it from) is more limited.

The code to assign the value to the static variable is run during the startup phase (not the setup function - before even that runs) - a process called "crt0" for "C RunTime phase 0".  This copies all the values for the pre-set (static and global) variables from flash into RAM, and that is the only time these initialization values are ever assigned.

In effect the "=0" of your static declaration is not performed there, but right at the start of the program before even setup() runs.
Good description, but comparing static to global , even as in functionality only, is IMHO iffy.
The main purpose of "static" variable  is - it gets allocated and ASSIGNED once.
And it has nothing to do with Arduino IDE Setup function, as you pointed out.
And its accessibility / scope is same as any other variable - has nothing to do with "static" either.



"Thunder is good, thunder is impressive; but it is lightning that does all the work"
Mark Twain

I do not read nor respond to thunderous posts.

Vaclav

i don't really get it,
i know from other languages that static or the world specific for that language means this variable can be used inside one function only, global means any functions can use it

i made a little search i found on a forum that they say a static variable means it can be used in 1 function only the one declared in, but can not be used in another unless it's not static

about your example i don't get it ! why is it .cpp and not .ino ?
and why would i have multiple files ?! you mean multiple tabs ?
and why would i have multiple files ?! you mean multiple tabs ?

Unfortunately yet another Arduino.inc coined term.

"Tab" is common name for GUI control, file contains your code.

Using multiple files is beneficial in organizing your code into logical, easier to manage units - for example one file blinks LED and another writes to LCD , yet another keeps your robot  moving etc. 

You can share files between applications - "code once , reuse many times " as another somewhat forgotten way to code software. Or you can call it "cut and paste" if you prefer.
"Thunder is good, thunder is impressive; but it is lightning that does all the work"
Mark Twain

I do not read nor respond to thunderous posts.

RayLivingston

And its accessibility / scope is same as any other variable - has nothing to do with "static" either.
No, that is not right.  It absolutely DOES limit scope to the current "block".  A static variable placed into a .c or .cpp file outside any function or block will be visible ONLY within that one file, and not to any other files linked into the build.  In c/c++, using static forces BOTH persistence, AND limited scope.

Regards,
Ray L.

Nick Gammon

and why would i have multiple files ?! you mean multiple tabs ?

Unfortunately yet another Arduino.inc coined term.

"Tab" is common name for GUI control, file contains your code.
Unfortunately, "tab" is a word with multiple meanings. For example you have a Tab key on your keyboard. You can "pay your tab" at the bar.

In the IDE if you make multiple tabs they become multiple files in the sketch directory.

See https://en.wiktionary.org/wiki/tab
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

pYro_65

#14
Sep 13, 2015, 06:33 am Last Edit: Sep 13, 2015, 06:34 am by pYro_65
In effect the "=0" of your static declaration is not performed there, but right at the start of the program before even setup() runs.
Bang! Relying on this statement will hurt one day.


What you are seeing is the result of link time optimizations. You should only expect the value to be set when the declaration is first encountered in normal code flow.

Code: [Select]
int func(){
  Serial.print("Or is this?");
  return 1;
}

void setup() {
  Serial.begin(9600);
  Serial.println("Is this printed first?");
}

void loop() {
  static int i = func();
}
https://forum.arduino.cc/index.php?action=dlattach;topic=327736.0;attach=128670 New EEPROM library released

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy