Chapter 13 Storage classes



Similar documents
Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Comp151. Definitions & Declarations

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

Keil C51 Cross Compiler

Object Oriented Software Design II

C++ INTERVIEW QUESTIONS

The C Programming Language course syllabus associate level

Sources: On the Web: Slides will be available on:

Chapter 5 Names, Bindings, Type Checking, and Scopes

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Glossary of Object Oriented Terms

El Dorado Union High School District Educational Services

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Java CPD (I) Frans Coenen Department of Computer Science

ECE 341 Coding Standard

The programming language C. sws1 1

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Course Title: Software Development

C++ Programming Language

Moving from CS 61A Scheme to CS 61B Java

Object Oriented Software Design II

Illustration 1: Diagram of program function and data flow

Install Java Development Kit (JDK) 1.8

Pemrograman Dasar. Basic Elements Of Java

Introduction to Object-Oriented Programming

1 Abstract Data Types Information Hiding

Curriculum Map. Discipline: Computer Science Course: C++

Informatica e Sistemi in Tempo Reale

/* File: blkcopy.c. size_t n

MISRA-C:2012 Standards Model Summary for C / C++

Lecture 9. Semantic Analysis Scoping and Symbol Table

Dalhousie University CSCI 2132 Software Development Winter 2015 Lab 7, March 11

Data Structures using OOP C++ Lecture 1

C Interview Questions

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

An Incomplete C++ Primer. University of Wyoming MA 5310

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

C Compiler Targeting the Java Virtual Machine

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

Outline Basic concepts of Python language

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Java (12 Weeks) Introduction to Java Programming Language

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

MPLAB TM C30 Managed PSV Pointers. Beta support included with MPLAB C30 V3.00

5 Arrays and Pointers

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Lecture 5: Java Fundamentals III

Using C to Access Data Stored in Program Space Memory on the TMS320C24x DSP

FEEG Applied Programming 5 - Tutorial Session

Threads Scheduling on Linux Operating Systems

Course Name: ADVANCE COURSE IN SOFTWARE DEVELOPMENT (Specialization:.Net Technologies)

CS 241 Data Organization Coding Standards

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Implementation Aspects of OO-Languages

13 Classes & Objects with Constructors/Destructors

OpenACC 2.0 and the PGI Accelerator Compilers

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CISC 181 Project 3 Designing Classes for Bank Accounts

Java Interview Questions and Answers

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Sample Report. Header Search. Search Information SSN: Found 27 records. Record # 1

Example of a Java program

Data Tool Platform SQL Development Tools

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Chapter 1 Java Program Design and Development

Coding Rules. Encoding the type of a function into the name (so-called Hungarian notation) is forbidden - it only confuses the programmer.

C++ Overloading, Constructors, Assignment operator

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

C PROGRAMMING FOR MATHEMATICAL COMPUTING

How To Write Portable Programs In C

COS 217: Introduction to Programming Systems

Compiler Construction

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

MatrixSSL Porting Guide

Motorola 8- and 16-bit Embedded Application Binary Interface (M8/16EABI)

Programing the Microprocessor in C Microprocessor System Design and Interfacing ECE 362

Chapter One Introduction to Programming

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Introduction to Java

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Programming Microcontrollers in C

Jonathan Worthington Scarborough Linux User Group

Computer Programming I

V850E2/ML4 APPLICATION NOTE. Performance Evaluation Software. Abstract. Products. R01AN1228EJ0100 Rev Aug. 24, 2012

JavaScript. JavaScript: fundamentals, concepts, object model. Document Object Model. The Web Page. The window object (1/2) The document object

Atmel AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers. 8-bit Atmel Microcontrollers. Application Note.

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

AP Computer Science A 2012 Scoring Guidelines

Transcription:

Chapter 13 Storage classes 1. Storage classes 2. Storage Class auto 3. Storage Class extern 4. Storage Class static 5. Storage Class register 6. Global and Local Variables 7. Nested Blocks with the Same Variable Name 8. Storage Classes for Multiple Source Files 9. Storage Classes for Functions 10. ANSI C Type Qualifiers

1. Storage classes The storage class of a variable is a set of properties about the variable. The storage class of a variable determines 3 things: scope: the sections of code that can use the variable. (i.e., variable visibility domain) linkage: how a variable can be used in a multiple source-file program. storage duration: how long the variable persists in memory. The storage class of a variable is determined by where it is defined and by what keyword (e.g. extern, auto, static, register) is used.

Scope of Variable A C variable has one of the following 3 scopes: file scope: the variable is visible from the point it is defined to the end of file containing the definition. block scope: the variable is visible from the point it is defined until the end of the block containing the definition. Function prototype scope: The variable is visible till the end of the function prototype declaration (int funct1(int a, double b);)

Example int global_var; /* global_var has file scope*/ double myfunction(int a; double b); /*a & b have function prototype scope */ main(void) { }... return 0; double myfunction(int x, double y) { } /* x, y have block scope */ double c=x + 3*y; /* c has block scope */ return c;

Linkage of Variables A C variable has one of the following linkages: external linkage: the variable can be used anywhere in a multifile program. internal linkage: the variable can be used anywhere in a single file. no linkage: the variable can be used only in the block in which it is defined. Variables with block scope or function prototype scope have no linkage.

Storage Duration of Variables The storage duration of a C variable can be: static storage duration: the variable exists throughout the program execution. automatic storage duration: the variable can exist only while the program is executing the block in which the variable is defined.

Example #include <stdio.h> int global_var = 5; /* static storage duration */ void function1(int var); main(void) { } function1(global_var); return 0; void function1(int var1) { /* var1 has auto storage */ } int var2; /* var2 has auto storage duration */ for (var2=0; var2<var1; var2++) puts( Welcome to C programming );

2. Storage Class auto The automatic variables have the following descriptions: They are defined as function arguments, e.g. k in fn(), or They are defined in a block. A block is a complex statement which begins with a { and ends with a }. The definition of automatic variables comes right after the {, e.g. i and j (next).

Example fn(int k) /* automatic var */ { } int i; /* automatic */ for (i=0; i<10; i++) { } int j; /* automatic */ for (j=0; j<4; j++) if (k%j==0) k++; return(k); /* j no longer available */

Properties An automatic variable has automatic storage: the life time of an automatic variable is only within the function or block it is defined in. Consequently, it has no meaning outside the function or block. It is called the local variable of the corresponding function or block. The automatic variables are deleted after execution of the corresponding function or block where they are defined. It is because they are no longer needed and memory occupied by the variables can be reused. Consequently, the value stored in an automatic variable is lost after exiting from a function or block.

Continued An automatic variable has block scope. Only the function in which the variable is defined can access that variable by name. An automatic variable has no linkage: The variable cannot be declared twice in the same block. An automatic variable can be defined explicitly using the keyword auto as

Example fn(int k) /* k automatic var */ { } auto int i; /* auto variable */ for (i=0; i<10; i++) { auto int j; /* auto variable */ for (j=0; j<4; j++) if (k%j==0) k++; } /* j invisible hereafter */ return(k);

3. Storage Class extern A variable defined outside a function is external. An external variable can also be declared inside a function that uses it by using the extern keyword. If the variable is defined in another file, or after the function definition, then declaring the variable with extern is mandatory.

Example double Earray[10]; /* externally defined array */ extern char Echar; /* mandatory declaration Echar is defined in another file */ int next(void); main(void) { } extern int Eint; /* mandatory declaration */ extern double Earray[]; /* optional declaration */ Eint += 10;... int Eint; /* externally defined variable */ void next(void) { } Eint++;... /* subsequent functions can use Eint */

Properties External variables have external linkage. External variables have static storage duration. For external variables, the compiler may not distinguish between upper- and lowercase, and it may recognize only the 1st 6 characters in a name.

4. Storage Class static The duration of a static variable is fixed. Static variables are created at the start of the program and are destroyed only at the end of program execution. Static variables can be defined inside or outside of a function. Here, we focus on the first case. #include <stdio.h> void function(); main(void) { int i; for (i=0; i<3; i++) function(); return 0; }

void function() { static int static_var=0; /* static variable */ int auto_var = 0; /* automatic variable */ ++static_var; ++auto_var; printf("the value of the static variable is: %d\n", static_var); printf("the value of the auto variable is: %d\n", auto_var); } $./Program output The value of the static variable is: 1 The value of the auto variable is: 1 The value of the static variable is: 2 The value of the auto variable is: 1 The value of the static variable is: 3 The value of the auto variable is: 1

5. Storage Class register An automatic variable can be defined using the keyword register as fn(register int k) { /* automatic var */ register int i; for (i=0; i<10; i++) { register int j; for (j=0; j<4; j++) if (k%j==0) k++; } return(k); }

Properties Inform the compiler that variables will be referenced on numerous occasions and, where possible, to use the CPU registers. Instructions using register variables executes faster than instructions that use no register variables. There are limited number of registers available. Applicable to automatic variables and function argument only Restricted to certain data types (is machine dependent), often int, char and pointer Not allowed to take address of register variables, i.e., & operator will not work with register variables.

6. Local and Global Variables Local variables: are variables defined inside a function. They have function or block scope Global variables: are variables defined outside the functions. They have file (or program) scope When should global variables be used? Advantages of using global variables: simplest way of communication between functions efficiency Disadvantages of using global variables: less readable program more difficult to debug and modify

Storage Classes for Different Variables Variables Keywords Scope Linkage Storage Duration automatic auto block no automatic external extern file/program external static static static file/block internal static register register block no automatic local none/auto/ static/register block global none/extern file no internal/ external automatic/ static static

7. Nested Blocks Variables are allowed to have the same name as long as they are defined under different scope or block A block may be nested with other blocks When variables with same name are declared in different nested blocks, the variables with smaller scope will temporarily hide the other variables within that block Local variables declared static still have block scope (although they exist from program start)

Example #include <stdio.h> main(void) { /* begin block 1 */ int i = 10; i += 10; printf("variable i in block 1 = %d\n", i); { /* begin block 2 */ int i = 100; i += 100; printf("variable i in block 2 = %d\n", i); { /* begin block 3 */ int i = 300; i += 300; printf("variable i in block 3 = %d\n", i); } /* end block 3 */ } /* end block 2 */ i += 10; printf("variable i in block 1 = %d\n", i); return 0; } /* end block 1 */

Program output Variable i in block 1 = 20 Variable i in block 2 = 200 Variable i in block 3 = 600 Variable i in block 1 = 30

Example modified #include <stdio.h> main(void) { /* begin block 1 */ int i = 10; i += 10; printf("variable i in block 1 = %d\n", i); { /* begin block 2 */ int i = 100; i += 100; printf("variable i in block 2 = %d\n", i); { /* begin block 3 */ // int i = 300; Commented out i += 300; printf("variable i in block 3 = %d\n", i); } /* end block 3 */ } /* end block 2 */ i += 10; printf("variable i in block 1 = %d\n", i); return 0; } /* end block 1 */

Program output Variable i in block 1 = 20 Variable i in block 2 = 200 Variable i in block 3 = 500 Variable i in block 1 = 30

8. Storage Classes for Multiple Source Files Multiple files can be used in C to store different pieces of codes of a single program One file may contain main() and some declaration; another may contain functions definitions and third may be a header file with prototypes and data structure declarations Consider the following multiple-sourcefile program:

#include <stdio.h> /* file1.c */ int index1; /* global to all files */ static int index2; /* global to file 1 */ main(void) { int i; /* auto */ extern int fn(int, int); /* fn() is in another source file*/ for (i=0; i<2; i++) { int j; /* auto */ for (j=1; j<2; j++) { index2 = fn(i, j); index1 = index2 + 1; printf("in Main index1 = %d, index2 = %d\n\n", index1, index2); } } return(0); }

/* file2.c */ #include <stdio.h> extern int index1; /* index1 is in another file */ fn(int i, int j) { int k; static int m=0; /*declare m to be static*/ k = index1; if (m == 0) printf("k is %d \t PRINTED ONLY ONCE \n\n", k); m++; printf("call number %d, m = %d, index1=%d\n\n", m, m, index1); return(m); }

A test run k is 0 PRINTED ONLY ONE TIME Call number 1, m = 1, index1 = 0 In Main index1 = 2, index2 = 1 Call number 2, m = 2, index1 = 2 In Main index1 = 3, index2 = 2

Properties The variable index1 is a global variable int index1; ( in file1.c ) The variable is visible to all functions and statements even if the functions are defined in different files For example, the statement index1 = index2 + 1; (in file1.c) Both file1.c and file2.c make use of the variable index1 although index1 is defined in file1.c

Continued However, global variables such has index1 defined in one file are not visible to other files, unless they are also declared in other files. For example, to define index1 in file1.c to be available to all files, index1 is declared as extern int index1; in file2.c. The keyword extern in file2.c declares that the real definition of index1 is not in file2.c but in other file. When the C compiler compile file2.c, it will treat index1 as if it has been defined in file2.c. We can use index1 in file2.c as k = index1; (in file2.c)

Continued Any variable can be given the static specifier as in file1.c. The variable is known as static global variable. static int index2; The keyword static has special meaning here. When a program consists of more than one file, the keyword static declared the following variable name, e.g., index2, invisible to other files. For example, index2 is invisible to file2.c but index1 is visible to file1.c and file2.c.

9. Storage Classes for Functions Functions can have storage classes: external (the default), or static e.g., double gamma(); extern double delta(); An external function can be accessed by functions in other files. A static function can be used only within the defining file. Examples: double gamma(); /*local & can be external */ static double beta(); /* local to the current file */ extern double delta(); /* defined in another file */

Localizing the Use of Variables and Functions C can localize information and functions in a file by defining functions and global variables as static. For example, int index1; /* program scope */ static int index2; /* file scope */ fn(...) { /* program scope: allow this function to be used in other part of the program */... } static int fn2(...) { /* file scope: do not want this function to be seen in other files */... }

10. ANSI C Type Qualifiers ANSI C adds 2 more properties to variables: constant volatile (for compiler optimization - Not discussed here) The const Type Qualifier The const keyword in a declaration establishes a variable whose value cannot be modified by assignment or by incrementing or decrementing. const int nochange; /* nochange is constant */ nochange = 12; /* not allowed */

Continued Constant variables can only be initialized at its declaration. const int nochange = 12; /* ok */ const int scores[5] = {70,54,34,23,65}; Pointer to constant Vs. Constant pointer Case 1: const float *pf; /* pf points to a constant float value */ The pointed-to value (i.e. *pf ) cannot be changed but the value of pf can change.

Continued Case 2: float * const pt; /* pt is a const pointer */ The value of pt cannot be changed but the pointed-to value (i.e. *pt ) can change. Case 3: const float * const ptr; Both ptr and *ptr cannot be changed.

Continued The const keyword is used in formal function parameters. For example, int strlen(const char *str); The declaration says that the string pointed to by str cannot be changed, but str can be changed. In other words, within the strlen(), it is possible to do things like str++. How do you interpret the following? char *strcat(char *, const char *);