Cloudbook: C

  1. Home
  2. Variables
  3. Modeling
  4. § 4 exercise →
Lifetime

The lifetime of a variable is the extent of time during which the variable location is allocated.

        	int f(int i) {
        		return (i<0)?-i:i ;
        	}
        
For the function f, the variable i is allocated when the control flow enters the function, i.e. the function is called, and it is deallocated at return from the function. If the function is entered multiple times, although scope would have it be the same variable, lifetime says that it is not: it is a new allocation of a variable of the same name.

The variables with static extent have lifetime that begins with the start of the program and continues until the program exists. The parameters to functions, such as i in the above example, or other local variables defined inside a function or block, have automatic extent. Locations are created and released for automatic extents according to the program flow.

Dynamic variables are those whose lifetime are under the explicit control of the program, and are used through pointers. Much of the difficulty of C is in the use of dynamic variables. While the syntax of scoping rules make it impossible to refer to out-of-lifetime variables that are governed by scoping rules, it is possible to attempt access to an out-of-lifetime variable using a pointer. It is always the programmer's responsibility that accesses to a dynamic variable are only made during the variable's lifetime.

Lifetime is a run-time property. Scope is a compile-time property. Scope determines which variable is being referred to, especially when there are several variables by the same name. This determination is made at compile-time, and once made, the compiler translates the program in such a way that the variable name is no longer needed. The variable names are thrown-away, unless retained for the purposes of a debugger, and the variable is associated with the address of the variable's location.

If the function calls itself, the same variable is being referred to, in terms of scope, but not in terms of extent. Each invocation of the function creates a distinct variable location, with a lifetime nested inside the lifetime of the previously begun variable, exactly according to the stack of recursive calls.