Identifiers Lifetimes Named entities and their binding to

Identifiers & Lifetimes Named entities and their binding to storage. 1

Use of Identifiers q What parts of a program have identifiers ("names")? n variables const int BUFSIZE = 1024; n constants static long total; n subprograms long count( int value ) { n labels sum: { n formal parameters while(value>0) n classes total += value--; } n whole programs? return total; } 2

Naming of Identifiers Do identifier names need to unique? n depends on scope of identifier, and n syntax of language: use must be unambiguous q Can an identifier use the name of a keyword? n yes, in some (older) languages n in current language design, keywords are reserved for clarity q (* In Pascal, identifier can be a keyword *) var integer: real; real: integer; begin real : = 2 + 3; (* integer arithmetic *) 3

What kind of identifier is "A"? (Java) Is the meaning of each identifier unambiguous? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class A A A { /* Stop waste! Conserve letters. */ A; ( ) { } (A A) { this. A = A; } A ( ) { return A; } A (A A) { A: if ( A. A( ) == A ) return A; else break A; return this. A; } public static void main(String [] a) { A A = new A( ); A. A = new A( A. A( ) ) ); } } 4

Lifetime is the duration of time that an entity (variable, constant, . . . ) is bound to memory. q Lifetime can be. . . n duration of process execution (static variables) n duration of object existence (object attributes) n duration of function activation (local variables) n duration of scope activation (variable defined in a scope). A function also defines a scope. q Lifetime applies to entities that have values, not names. q "Lifetime of an identifier" doesn't make sense. . . identifiers have "scope" rather than "lifetime". q 5

Lifetime and Scope of identifiers and lifetime of entity it refers to are not the same. q Lifetime: time when entity exists in memory q scope: the parts of a program where a name is known or "visible" void add( int count ) { static long SUM = 0; float x = 0. 5; while(count>0) { int x = 2; SUM += x*count; count--; } printf("%f", x); } count: scope is function add( ), lifetime unknown. SUM: scope is function body, lifetime is process execution time. float x: scope is part of the function excluding while loop, lifetime is function activation time. int x: scope is while loop, lifetime is duration of while loop. 6

Lifetime and Scope (2) q q BUFSIZE has global scope (any file in this program can refer to its value). Its lifetime is the process's lifetime. buf has file scope. Its lifetime is the program's lifetime. length , k: scope is the function, lifetime is duration of function. c: scope is the for loop. Life is duration of "for" loop execution. int BUFSIZE = 1024; static char buf[BUFSIZE]; void read( int length ) { int k; for(k=0; k<length; k++) { int c = getchar(); if (c<0) break; buf[k] = c; } buf[k] = '