Duration

Duration, closely related to a storage class, defines a period during which the declared identifiers have real, physical objects allocated in memory. We also distinguish between compile-time and run-time objects. Variables, for instance, unlike typedefs and types, have real memory allocated during run time. There are two kinds of duration: static and local.

Static Duration

Memory is allocated to objects with static duration as soon as execution is underway; this storage allocation lasts until the program terminates. Static duration objects usually reside in fixed data segments allocated according to the memory model in force. All globals have static duration. All functions, wherever defined, are objects with static duration. Other variables can be given static duration by using the explicit static or extern storage class specifiers.

In the mikroC PRO for 8051, static duration objects are not initialized to zero (or null) in the absence of any explicit initializer.

Don’t mix static duration with file or global scope. An object can have static duration and local scope – see the example below.

Local Duration

Local duration objects are also known as automatic objects. They are created on the stack (or in a register) when an enclosing block or a function is entered. They are deallocated when the program exits that block or function. Local duration objects must be explicitly initialized; otherwise, their contents are unpredictable.

The storage class specifier auto can be used when declaring local duration variables, but it is usually redundant, because auto is default for variables declared within a block.

An object with local duration also has local scope because it does not exist outside of its enclosing block. On the other hand, a local scope object can have static duration. For example:

void f() {
  /* local duration variable; init a upon every call to f */
  int a = 1;
  /* static duration variable; init b only upon first call to f */
  static int b = 1;
  /* checkpoint! */
  a++;
  b++;
}

void main() {
/* At checkpoint, we will have: */
f(); // a=1, b=1, after first call,
f(); // a=1, b=2, after second call,
f(); // a=1, b=3, after third call,
     // etc. 
}
Copyright (c) 2002-2013 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code