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

Slides:



Advertisements
Similar presentations
Instruction Set Design
Advertisements

1 Lecture 4: Procedure Calls Today’s topics:  Procedure calls  Large constants  The compilation process Reminder: Assignment 1 is due on Thursday.
Names and Bindings.
Prof. Necula CS 164 Lecture 141 Run-time Environments Lecture 8.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
CS1372: HELPING TO PUT THE COMPUTING IN ECE CS1372 Memory.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
1 Review of Class on Oct Outline  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
CS 536 Spring Run-time organization Lecture 19.
3/17/2008Prof. Hilfinger CS 164 Lecture 231 Run-time organization Lecture 23.
Run-Time Storage Organization
Run time vs. Compile time
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Processes CS 416: Operating Systems Design, Spring 2001 Department of Computer Science Rutgers University
Operating Systems Concepts 1. A Computer Model An operating system has to deal with the fact that a computer is made up of a CPU, random access memory.
Storage & Linkage: Effects on Scope Rudra Dutta CSC Spring 2007, Section 001.
C++ for Engineers and Scientists Third Edition
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
CS 403: Programming Languages Lecture 2 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
CSC3315 (Spring 2009)1 CSC 3315 Programming Languages Hamid Harroud School of Science and Engineering, Akhawayn University
Copyright 2001 Oxford Consulting, Ltd1 January Storage Classes, Scope and Linkage Overview Focus is on the structure of a C++ program with –Multiple.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Runtime Environments Compiler Construction Chapter 7.
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
ITEC 352 Lecture 18 Functions in Assembly. Functions + Assembly Review Questions? Project due on Friday Exam –Average 76 Methods for functions in assembly.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
18. DECLARATIONS.
Learners Support Publications Classes and Objects.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Memory: Relocation.
Advanced Java Programming CS 537 – Data Structures and Algorithms.
Run-Time Storage Organization Compiler Design Lecture (03/23/98) Computer Science Rensselaer Polytechnic.
COMP3190: Principle of Programming Languages
Operating System Principles And Multitasking
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Processes CS 6560: Operating Systems Design. 2 Von Neuman Model Both text (program) and data reside in memory Execution cycle Fetch instruction Decode.
WEL COME PRAVEEN M JIGAJINNI PGT (Computer Science) MTech[IT],MPhil (Comp.Sci), MCA, MSc[IT], PGDCA, ADCA, Dc. Sc. & Engg.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
+ Storage Classes and Linkage. + Introduction Scope describe the region or regions of a program that can access and identifier Variables can be shared.
CS 330 Programming Languages 10 / 23 / 2007 Instructor: Michael Eckmann.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
LECTURE 19 Subroutines and Parameter Passing. ABSTRACTION Recall: Abstraction is the process by which we can hide larger or more complex code fragments.
Memory Management.
Eine By: Avinash Reddy 09/29/2016.
Object Lifetime and Pointers
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Processes and threads.
CSE 374 Programming Concepts & Tools
ENERGY 211 / CME 211 Lecture 25 November 17, 2008.
COM S 326X Deep C Programming for the 21st Century Prof. Rozier
Run-time organization
Storage class in C Topics Automatic variables External variables
Chapter 5 Conclusion CIS 61.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Memory Allocation CS 217.
Classes and Objects.
C Storage classes.
Storage class.
Binding Times Binding is an association between two things Examples:
COMP755 Advanced Operating Systems
The Three Attributes of an Identifier
Storage classes in C In C language, each variable has a storage class which decides the following things: scope i.e where the value of the variable would.
Storage Classes.
Presentation transcript:

CS 2130 Lecture 5 Storage Classes Scope

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

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).

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

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?

"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

"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???

"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"

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.

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 */ }

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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 ”

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

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

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

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

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?

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

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

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

Questions?

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); }