Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 2130 Lecture 5 Storage Classes Scope. C Programming C is not just another programming language C was designed for systems programming like writing.

Similar presentations


Presentation on theme: "CS 2130 Lecture 5 Storage Classes Scope. C Programming C is not just another programming language C was designed for systems programming like writing."— Presentation transcript:

1 CS 2130 Lecture 5 Storage Classes Scope

2 C Programming C is not just another programming language C was designed for systems programming like writing operating systems, device drivers, Hello, World, etc. Some don't even consider it a high level language C allows you unparalleled access and control of the machine hardware. [Almost assembly] C does not have many built-in error checking features This is why –C is so powerful –C is so fast –C is so dangerous

3 Typical High Level Languages Try to separate the programmer from the hardware Keep track of many things "behind the scenes" C allows the programmer to specify special ways that certain variables should be handled C also treats variable differently depending on where they are declared Understanding this concept is critical to success when writing C programs (that work).

4 Storage Classes volatileregister constauto staticextern Technically, const and volatile are type qualifiers, but will be discussed here

5 volatile Used to indicate possibility that this variable might be changed by someone else int n = 42; /* some code that doesn’t modify n */ if(n == 42) { printf(“life, universe, everything”); } We would expect n to be 42 So optimization might pull n into a register and not recheck. Good thing or bad thing?

6 "Pull n into a register?" register - a storage location located as part of the CPU. Normally all computation is performed by moving values from memory into registers and then performing calculations with registers as operands. Simplified picture Memory Registers ALU

7 "Pull n into a register?" Typical Assembly Language Sequence MOVE R2, 42# Put 42 in Reg 2 STORER2, N# Store Reg 2 in N...# Code not using N LOADR2, N# Fetch N into Reg 2 CMPR2, 42# N == 42??? BNEELSE# No, skip "then" Can this be optimized???

8 "Pull n into a register?" Typical Assembly Language Sequence MOVE R2, 42# Put 42 in Reg 2 STORER2, N# Store Reg 2 in N...# Code not using N # (Don't use R2) LOADR2, N# Fetch N into Reg 2 CMPR2, 42# N == 42??? BNEELSE# No, skip "then"

9 But......what if the memory location containing N can be accessed by something else? –Could be shared memory –Could be IO Device Volatile storage class warns compiler to assume value may be changed by something else.

10 Conversely What if a particular variable needs to be accessed very frequently? Usually the compiler will recognize this and keep the variable in a register int i; for(i=0; i<100000; i++) { /* loop */ }

11 Conversely To suggest to the compiler that this is a good idea: register register int i; for(i=0; i<100000; i++) { /* loop */ } The register keyword suggests to the compiler that a variable should be maintained in a register as opposed to memory.

12 register Since putting one variable in a register can speed up execution putting more variables in registers can only make things better!?!?!? Fact: Overuse of “register” can adversely affect the compiler’s register allocation algorithm Don't try and outwit the compiler! In some isolated cases it is possible to improve performance: i.e. dumb compiler

13 register Also, cannot get the address of a variable declared to be in the register storage class: int i, *ip; ip = & i;/* (more later) */ In most cases use of register is discouraged

14 Storage Classes volatile register const auto static extern Consider memory Consider memory

15 Memory Representation We typically draw diagrams representing the memory of the computer, our particular program or both as rectangles. Our convention will be that "low-memory" will be on the bottom and "high- memory" on top. Typically these drawings are not to scale High Memory Low Memory

16 Typical Arrangement Normally the actual program code (executable instructions) is placed in low memory Code

17 Typical Arrangement Next we have an area for storage of constant data Code Constant Data

18 Typical Arrangement Data that may be changed follows Code Constant Data Alterable Data

19 Typical Arrangement These three items comprise what is considered the static area of memory. The static area details (size, what is where, etc.) are known at translation or compile time. Code Constant Data Alterable Data Static

20 Typical Arrangement Immediately above the static area the heap is located. The heap can expand upward as the program dynamically requests additional storage space In most cases, the runtime environment manages the heap for the user Code Constant Data Alterable Data Static Heap

21 Typical Arrangement Finally, the stack starts in high memory and can grow down as space is needed. Items maintained in the stack include –Local variables –Function parameters –Return values Code Constant Data Alterable Data Static Heap Stack

22 Typical Arrangement These items in the upper portion of the diagram change during execution of the program. Thus they are called dynamic Code Constant Data Alterable Data Static Heap Stack Dynamic

23 const Items to be maintained in the Constant Data area are designated by the programmer with the const keyword WARNING!!! It is possible (and relatively easy) to modify data designated as const Code Constant Data Alterable Data Static Heap Stack Dynamic

24 auto auto, short for automatic variables are those that exist on the stack. The auto keyword is not normally used. Automatic means that space is allocated and deallocated on the stack automatically without the programmer having to do any special operations. Code Constant Data Alterable Data Static Heap Stack Dynamic

25 auto int foo(int z) { int x;... if(x == z) { int y; y =... auto variables (implicitly)

26 static static variables exist in an area of memory set aside for alterable (or readable/writeable) data static can have different meanings depending on where used. Code Constant Data Alterable Data Static Heap Stack Dynamic

27 static Variables –A global variable is stored in the static area of memory –A variable that is global just to the functions in one file must be designated using static –A variable that is local to a function AND retains its value (i.e. persistence) must be labeled static Functions –A function labeled as static is visible only within the file where it is defined

28 static int i; /* Global variable...stored in * static area (storage class is * static */ int foo(...) {... } int main() {... }

29 Multiple Files foo.cbar.cbaz.c Linker a.out Advantage: For maintenance only have to recompile affected files Advantage: For maintenance only have to recompile affected files

30 Multiple File Scope Scope can be Global within a file Scope can be Global across all files Scope can be defined illegally!

31 Scope can be Global within a file static int i; int foo(...) {... } int bar(...) {... } static int i; int main() {... } int baz(...) {... } These are different variables with Global scope within their respective files These are different variables with Global scope within their respective files

32 Scope can be Global across all files int i;extern int i; These are the same variable with Global scope across all files. Note: Variable is defined in one file and defined as extern in the rest. These are the same variable with Global scope across all files. Note: Variable is defined in one file and defined as extern in the rest.

33 Scope can be defined illegally! int i; Without specifically defining these variables as static or extern the linker will generate an error message Without specifically defining these variables as static or extern the linker will generate an error message

34 Scope vs. Lifetime Scope Program Scope File Scope Function Scope Block Scope Lifetime Life of Program Life of program Life of function Life of block

35 Scope vs. Lifetime Scope Program Scope File Scope Function Scope Block Scope Lifetime Life of Program Life of program Life of function Life of block Can be overridden with “ static ”

36 Memory Many languages have fixed mappings between scopes and lifetimes In C, we have the option to decide... void foo(void) { int x; static int a; x = 42; When the function goes away, x and its value go away since they were on stack. Setting a value into a static variable (e.g. a) means that the value is stored in a static area and will remain

37 Memory Static variables are like global variables except for scope. That is, they have the same lifetime. Static initialization? Is this an issue?

38 Static Initialization void foo(void) { int x = 10; static int y = 20; Both variables are initialized as allocated x is initialized to 10 every time function foo runs y is initialized when program starts

39 Static Initialization? void foo(void) { int x = 10; static int y; y = 20; This would defeat purpose of static variable having persistence!

40 Static Initialization void foo(void) { int x = 10; static int y = 20; printf(“x = %d y = %d\n”, x, y); y += 30; } What prints the first time foo is called? What prints the second time?

41 Static also applies to functions Static has different meanings depending on where used #include... #define int x; static int y; // Scope only in this file void foo(void) { static int z; // Persistent... } static void bar(void) // Only this file

42 Memory C does not have Garbage Collection Static storage can be calculated at translation time All other storage requirements determined at run time A program that allocates memory and then fails to keep track of what's been allocated is said to have a memory leak. This is an ERROR! Why are memory leaks important? –Multi-tasking Bad Thing ® –Running out of memory is a Bad Thing ® Why not have automatic Garbage Collection? –Overhead –Speed

43 Similarities with Java? One file: int i;/* Global */ static int j;/* File only */ void foo(...) static void bar(...) Another File: extern int i; static int j; If a variable does not need to be global across files MAKE IT STATIC public private public private

44 Questions?

45

46 int main() { int i; for(i = -2; i < 40; i++) printf("%d %d\n", i, fib(i)); } int fib(int n) { if(n <= 0) return -1 else return fib_h(n); } int fib_h(int n) { if(n == 1 || n == 2) return 1; else return fib_h(n-1) + fib_h(n-2); }


Download ppt "CS 2130 Lecture 5 Storage Classes Scope. C Programming C is not just another programming language C was designed for systems programming like writing."

Similar presentations


Ads by Google