M.EC201 Programming language

Similar documents
M.CS201 Programming language

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

CSE 230 Intermediate Programming in C and C++ Functions

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

CS201 Some Important Definitions

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part II

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

QUIZ. What is wrong with this code that uses default arguments?

Review of the C Programming Language for Principles of Operating Systems

Lecture 3: C Programm

Object oriented programming C++

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

M.CS201 Programming language

Here's how you declare a function that returns a pointer to a character:

BLM2031 Structured Programming. Zeyneb KURT

Programming Languages

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

University of Kelaniya Sri Lanka

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

CS240: Programming in C

LESSON 6 FLOW OF CONTROL

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.

Goals of this Lecture

Object-Oriented Principles and Practice / C++

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

C: How to Program. Week /Mar/05

Variables. Data Types.

Unit 7. Functions. Need of User Defined Functions

12 CREATING NEW TYPES

Review of the C Programming Language

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Model Viva Questions for Programming in C lab

Administrivia. Introduction to Computer Systems. Pointers, cont. Pointer example, again POINTERS. Project 2 posted, due October 6

Introduction to C++ with content from

Chapter 2 - Introduction to C Programming

CS561 Manju Muralidharan Priya Structures in C CS200 STRUCTURES. Manju Muralidharan Priya

Fundamentals of Programming Session 12

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Chapter 8: Intraprogram Communication. Lecture 8 1

CE221 Programming in C++ Part 1 Introduction

Algorithms & Data Structures

Procedural programming with C

M.CS201 Programming language

Computers Programming Course 5. Iulian Năstac

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

COMPUTER APPLICATION

Chapter 1 & 2 Introduction to C Language

OBJECTIVE QUESTIONS: Choose the correct alternative:

Programming Fundamentals (CS-302 )

UNIT 3 FUNCTIONS AND ARRAYS

M3-R4: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

Object oriented programming with C++

Sums. Here's a (poor) program to add three numbers

printf( Please enter another number: ); scanf( %d, &num2);

EL2310 Scientific Programming

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

Week 3 Lecture 2. Types Constants and Variables

In addition to name. Each variable in C program is characterized by its Type Scope Storage Class. Type Have already discussed

Programming for Engineers Introduction to C

Fundamentals of Programming & Procedural Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Functions. Systems Programming Concepts

just a ((somewhat) safer) dialect.

Functions. (transfer of parameters, returned values, recursion, function pointers).

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

CS 2505 Computer Organization I Test 1. Do not start the test until instructed to do so! printed

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

UNIT III (PART-II) & UNIT IV(PART-I)

Structures and Pointers

CS201 Latest Solved MCQs

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

DECLARAING AND INITIALIZING POINTERS

Tokens, Expressions and Control Structures

Cpt S 122 Data Structures. Introduction to C++ Part II

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

EL6483: Brief Overview of C Programming Language

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

Basic Types, Variables, Literals, Constants

CS240: Programming in C

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Fundamental of Programming (C)

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

Principles of C and Memory Management

INTRODUCTION 1 AND REVIEW

CMPE-013/L. Introduction to C Programming. Unit testing

Pointers and References

III. Classes (Chap. 3)

What have we learned about when we learned about function parameters? 1-1

Data types, variables, constants

Transcription:

Power Engineering School M.EC201 Programming language Lecture 13 Lecturer: Prof. Dr. T.Uranchimeg

Agenda The union Keyword typedef and Structures What Is Scope? External Variables 2

The union Keyword The union keyword is used for declaring unions. A union is a collection of one or more variables (union_members) that have been grouped under a single name. In addition, each of these union members occupies the same area of memory. 3

An instance The keyword union identifies the beginning of a union definition. It's followed by a tag that is the name given to the union. Following the tag are the union members enclosed in braces. An instance, the actual declaration of a union, also can be defined. If you define the structure without the instance, it's just a template that can be used later in a program to declare structures. 4

The format The following is a template's format: union tag { }; union_member(s); /* additional statements may go here */ 5

Template To use the template, you would use the following format: union tag instance; To use this format, you must have previously declared a union with the given tag. 6

Example 1 7

Example 2 8

Example 3 9

A practical use of a union #include <stdio.h> #define CHARACTER C #define INTEGER #define FLOAT struct generic_tag{ char type; I F 10

}; union shared_tag { char c; int i; float f; } shared; Cont. 2 11

Cont. 3 void print_function( struct generic_tag generic ); main () { struct generic_tag var; var.type = CHARACTER; 12

var.shared.c = `$'; Cont. 4 print_function( var ); var.type = FLOAT; var.shared.f = (float) 12345.67890; print_function( var ); var.type = `x'; 13

Cont. 5 var.shared.i = 111; print_function( var ); return 0; } void print_function( struct generic_tag generic ) 14

Cont. 6 { printf("\n\nthe generic value is..."); switch( generic.type ) { case CHARACTER: printf("%c", generic.shared.c); 15

Cont. 7 break; case INTEGER: printf("%d", generic.shared.i); break; case FLOAT: printf("%f", generic.shared.f); 16

Cont. 8 break; default: printf("an unknown type: %c\n", generic.type); break; } } 17

typedef and Structures You can use the typedef keyword to create a synonym for a structure or union type. For example, the following statements define coord as a synonym for the indicated structure: 18

An instance You can then declare instances of this structure using the coord identifier: coord topleft, bottomright; 19

The different Note that a typedef is different from a structure tag, as described earlier in this chapter. If you write 20

Explain the identifier coord is a tag for the structure. You can use the tag to declare instances of the structure, but unlike with a typedef, you must include the struct keyword: struct coord topleft, bottomright; 21

User types Whether you use typedef or a structure tag to declare structures makes little difference. Using typedef results in slightly more concise code, because the struct keyword doesn't need to be used. On the other hand, using a tag and having the struct keyword explicit makes it clear that it is a structure being declared. 22

What Is Scope? The scope of a variable refers to the extent to which different parts of a program have access to the variable--in other words, where the variable is visible. When referring to C variables, the terms accessibility and visibility are used interchangeably. When speaking about scope, the term variable refers to all C data types: simple variables, arrays, structures, pointers, and so forth. It also refers to symbolic constants defined with the const keyword. 23

Lifetime Scope also affects a variable's lifetime: how long the variable persists in memory, or when the variable's storage is allocated and deallocated. First, this chapter examines visibility. 24

Why Is Scope Important? To understand the importance of variable scope, you need to recall the discussion of structured programming on Day 5. The structured approach, you might remember, divides the program into independent functions that perform a specific task. The key word here is independent. 25

Variables For true independence, it's necessary for each function's variables to be isolated from interference caused by other functions. Only by isolating each function's data can you make sure that the function goes about its job without some other part of the program throwing a monkey wrench into the works. 26

External Variables An external variable is a variable defined outside of any function. This means outside of main() as well, because main() is a function, too. Until now, most of the variable definitions in this book have been external, placed in the source code before the start of main(). External variables are sometimes referred to as global variables. 27

When to Use External Variables Although the sample programs to this point have used external variables, in actual practice you should use them rarely. Why? Because when you use external variables, you are violating the principle of modular independence that is central to structured programming. Modular independence is the idea that each function, or module, in a program contains all the code and data it needs to do its job. 28

Some moments With the relatively small programs you're writing now, this might not seem important, but as you progress to larger and more complex programs, overreliance on external variables can start to cause problems. 29

External variables When should you use external variables? Make a variable external only when all or most of the program's functions need access to the variable. Symbolic constants defined with the const keyword are often good candidates for external status. If only some of your functions need access to a variable, pass the variable to the functions as an argument rather than making it external. 30

The extern Keyword When a function uses an external variable, it is good programming practice to declare the variable within the function using the extern keyword. The declaration takes the form extern type name; in which type is the variable type and name is the variable name. 31

The external variable x is declared as extern within the functions main() and print_value(). #include <stdio.h> int x = 999; void print_value(void); main() { extern int x; 32

} printf("%d\n", x); print_value(); return 0; Cont. 2 void print_value(void) {extern int x; printf("%d\n", x); } 33

Local Variables A local variable is one that is defined within a function. The scope of a local variable is limited to the function in which it is defined. Local variables aren't automatically initialized to 0 by the compiler. If you don't initialize a local variable when it's defined, it has an undefined or garbage value. You must explicitly assign a value to local variables before they're used for the first time. 34

Static Versus Automatic Variables Local variables are automatic by default. This means that local variables are created anew each time the function is called, and they are destroyed when execution leaves the function. What this means, in practical terms, is that an automatic variable doesn't retain its value between calls to the function in which it is defined. 35

Explain Suppose your program has a function that uses a local variable x. Also suppose that the first time it is called, the function assigns the value 100 to x. Execution returns to the calling program, and the function is called again later. Does the variable x still hold the value 100? No, it does not. The first instance of variable x was destroyed when execution left the function after the first call. When the function was called again, a new instance of x had to be created. The old x is gone. 36

Example What if the function needs to retain the value of a local variable between calls? For example, a printing function might need to remember the number of lines already sent to the printer to determine when a new page is needed. In order for a local variable to retain its value between calls, it must be defined as static with the static keyword. 37

Prototype void func1(int x) { static int a; /* Additional code goes here */ } 38

The difference between automatic and static local variables #include <stdio.h> void func1(void); main() { int count; for (count = 0; count < 20; count++) 39

} { } Cont. 2 printf("at iteration %d: ", count); func1(); return 0; 40

void func1(void) { } static int x = 0; int y = 0; Cont. 3 printf("x = %d, y = %d\n", x++, y++); 41

The Scope of Function Parameters A variable that is contained in a function heading's parameter list has local scope. For example, look at the following function: 42

Explian Both x and y are local variables with a scope that is the entire function func1(). Of course, x initially contains whatever value was passed to the function by the calling program. Once you've made use of that value, you can use x like any other local variable. Because parameter variables always start with the value passed as the corresponding argument, it's meaningless to think of them as being either static or automatic. 43

External Static Variables You can make an external variable static by including the static keyword in its definition: 44

Variables The difference between an ordinary external variable and a static external variable is one of scope. An ordinary external variable is visible to all functions in the file and can be used by functions in other files. A static external variable is visible only to functions in its own file and below the point of definition. 45

Register Variables The register keyword is used to suggest to the compiler that an automatic local variable be stored in a processor register rather than in regular memory. What is a processor register, and what are the advantages of using it? 46

CPU The central processing unit (CPU) of your computer contains a few data storage locations called registers. It is in the CPU registers that actual data operations, such as addition and division, take place. To manipulate data, the CPU must move the data from memory to its registers, perform the manipulations, and then move the data back to memory. Moving data to and from memory takes a finite amount of time. If a particular variable could be kept in a register to begin with, manipulations of the variable would proceed much faster. 47

The register By using the register keyword in the definition of an automatic variable, you ask the compiler to store that variable in a register. Look at the following example: 48

Explain Note that I said ask, not tell. Depending on the program's needs, a register might not be available for the variable. In this case, the compiler treats it as an ordinary automatic variable. The register keyword is a suggestion, not an order. The benefits of the register storage class are greatest for variables that the function uses frequently, such as the counter variable for a loop. 49

Property The register keyword can be used only with simple numeric variables, not arrays or structures. Also, it can't be used with either static or external storage classes. You can't define a pointer to a register variable. 50

Which Storage Class Should You Use? When you're deciding which storage class to use for particular variables in your programs, it might be helpful to refer to Table 51

C's five variable storage classes 52

Auto storage When you're deciding on a storage class, you should use an automatic storage class whenever possible and use other classes only when needed. Here are some guidelines to follow: Give each variable an automatic local storage class to begin with. 53

Cont. If the variable will be manipulated frequently, add the register keyword to its definition. In functions other than main(), make a variable static if its value must be retained between calls to the function. If a variable is used by most or all of the program's functions, define it with the external storage class. 54

Summary The union Keyword typedef and Structures What Is Scope? External Variables 55

Any questions? 56

Thank you for attention 57