Chapter 5 b Attributes of variables 1 Attributes
Chapter 5 -b • Attributes of variables 1
Attributes of variables Symbol Table { int sum = 5; . . . } Identifier Type sum int 0110 0010 Address 0000 0101 Value Storage 2
Variable Names sum=0. 0 DO I = 1 TO 10 sum = sum + i END DO. . . t = SQR(SUM). . . • Names: Fortran is not case sensitive. • Type: Fortran allows implicit declarations. FUNCTION sqr(val) val = val*val RETURN VAL 3
Naming Conventions Method names start with lower case public void action. Performed (Action. Event e){ int value = Math. PI; . . . } Class names start with upper case Constants are all upper case Local variables are all lower case 4
Aliasing: Variables union { short i; float f; char c; } uval; c i f uval Aliasing using variables is meant for conserving storage space. 5
Aliasing: Pointers int i; int *p=&i; char *c; c=(char*)p; i p c Aliasing using pointer variables is not meant for conserving storage space. 6
Static Variables (Fortran) SUBROUTINE fun() DATA k/0/ K=K+1 PRINT *, K RETURN Call statement CALL FUN(). . . Output 1 2 3 4 In Fortran, all variables are by default static 7
Static Variables (C) void fun(){ int k=0; k++; printf(“n %d”, k); } Call statement fun( ); . . . void fun(){ static int k=0; k++; printf(“n %d”, k); } fun( ); . . . Output 1 1 1 2 3 4 8
Stack Dynamic Variables { int i; . . . { int j; . . . }. . . i j i i } 9
Recursion 3 6 int fact (int n){ if(n==1) return 1; else return n*fact(n-1); } n=3 2 2 n=3 int fact (int n){ if(n==1) return 1; else return n*fact(n-1); } 1 n=2 n=3 1 int fact (int n){ if(n==1) return 1; else return n*fact(n-1); } n=1 n=2 n=3 10
Heap-Dynamic Variables (1) int size=100; int *p; p = (int *) malloc(size*2); . . . free(p); p p 0 99 ? ? Heap allocation requires effective memory management 11
Heap-Dynamic Variables (2) int *node; node = new int; //Allocates an int cell. . . . delete node; //free the allocated memory. Stack s = new Stack(); C++ Java 12
Scope (C) int x; . . . main(){ int k; . . . } Global variable Local variable 13
Scope (Java) public float fun(){ int[] x = {10, 20, 30}; float sum=0; for (int i=0; i<3; i++){ sum=sum+x[i]; } System. out. println(“Sum=”+sum); float v; v=sum/2; return v; } Local variables 14
Scope (Java classes) public class Myclass{ public void add(int y){ x = x+y; } int x=10; } Java allows the above type of declaration of instance variables but it is not advised. 15
Scope Vs. Lifetime (1) void compute() { static int k; . . . } Scope of the variable is limited to the function block, while its lifetime is the same as the total program execution time. 16
Scope Vs. Lifetime (2) void compute() { int value; . . . printinfo(); . . . } void printinfo(){. . . } Scope of “value” does not extend to the function “printinfo”, but lifetime of value does. 17
- Slides: 17