Binghamton University. CS-211 Fall Variable Scope

Similar documents
Binghamton University. CS-211 Fall Variable Scope

Binghamton University. CS-211 Fall Variable Scope

Procedures, Parameters, Values and Variables. Steven R. Bagley

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

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

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

G52CPP C++ Programming Lecture 6. Dr Jason Atkin

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

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

C Language, Token, Keywords, Constant, variable

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

PROGRAMMAZIONE I A.A. 2017/2018

C: How to Program. Week /Mar/05

A Fast Review of C Essentials Part I

Introduction to C++ with content from

COMP 2355 Introduction to Systems Programming

Chapter 2 - Introduction to C Programming

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

Chapter 11 Introduction to Programming in C

C++ for Java Programmers

Binghamton University. CS-211 Fall Functions. The Basis of C

PROGRAMMAZIONE I A.A. 2018/2019

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

CSE 374 Programming Concepts & Tools

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Chapter 11 Introduction to Programming in C

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

BLM2031 Structured Programming. Zeyneb KURT

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

Syntax and Variables

Course organization. Course introduction ( Week 1)

IV Unit Second Part STRUCTURES

Chapter 11 Introduction to Programming in C

CSE 303: Concepts and Tools for Software Development

Chapter 11 Introduction to Programming in C

CS 0449 Sample Midterm

Computer Systems Principles. C Pointers

Two s Complement Review. Two s Complement Review. Agenda. Agenda 6/21/2011

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

C library = Header files + Reserved words + main method

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

QUIZ. What are 3 differences between C and C++ const variables?

Functions in C C Programming and Software Tools

Chapter 11 Introduction to Programming in C

CS 61c: Great Ideas in Computer Architecture

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

CS349/SE382 A1 C Programming Tutorial

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

Program Organization and Comments

Programming in C. Pointers and Arrays

Chapter 1 & 2 Introduction to C Language

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Problem Solving and 'C' Programming

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

Chapter 11 Introduction to Programming in C

Data Structures Unit 02

Binghamton University. CS-211 Fall Object Orientation

Review of the C Programming Language for Principles of Operating Systems

CS 222: More File I/O, Bits, Masks, Finite State Problems

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

Supporting Class / C++ Lecture Notes

M.EC201 Programming language

Writing Functions in C

Tokens, Expressions and Control Structures

Strings. Compare these program fragments:

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

CPSC 427: Object-Oriented Programming

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

First of all, it is a variable, just like other variables you studied

Everything Else C Programming and Software Tools. N.C. State Department of Computer Science

Topics Introduction to Microprocessors

UNIT-V. Structures. The general syntax of structure is given below: Struct <tagname> { datatype membername1; datatype membername2; };

Compiling and Running a C Program in Unix

Arrays and Pointers in C. Alan L. Cox

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Kurt Schmidt. October 30, 2018

CS 223: Data Structures and Programming Techniques. Exam 2

Overview (1A) Young Won Lim 9/14/17

ELEC 377 C Programming Tutorial. ELEC Operating Systems

Algorithms, Data Structures, and Problem Solving

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Overview (1A) Young Won Lim 9/9/17

DS Assignment I. 1. Set a pointer by name first and last to point to the first element and last element of the list respectively.

Presented By : Gaurav Juneja

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

COMP322 - Introduction to C++

Why C++ is much more fun than C (C++ FAQ)?

Understanding Pointers

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

Transcription:

Variable Scope 1

Scope The places in your code that can read and/or write a variable. Scope starts at the location where you declare the variable There may be holes in the scope! Scope ends at the end of the block in which the declare occurs Usually, the function in which the variable was declared 3

Simple Example Block in which j is declared #include <stdio.h> int main(int argc, char **argv) { int j; for(j=0; j<argc; j++) { printf( Argument %d = %s\n,j,argv[j]); } return 0; } Scope of j 4

Block doesn t have to be a function! You can define a variable inside a sub-block of a function 5

Internal Example Block in which k is declared #include <stdio.h> int main(int argc, char **argv) { int j; for(j=0; j<argc; j++) { int k=j+1; printf( Argument %d = %s\n,k,argv[j]); } return 0; } Scope of k 6

Global Variable Declared outside of a block Scope is from declaration to the end of the C file! 7

Global Example Block in which nc is declared #include <stdio.h> int nc=0; int myfunc(int n) { nc++; return n; } int main(int argc, char **argv) { int j; for(j=0; j<argc; j++) myfunc(2); printf( myfunc called %d times\n,nc); return 0; } Scope of nc 8

Global Variable Pros & Cons Advantages Simple and intuitive Enables functions to communicate data with each other Remembers between function calls as well as within function calls Disadvantages Increases the outside information a function needs to be aware of (binding) Prevents re-use of functions Remembers between function calls as well as within function calls 9

Holes in Scopes If the same variable is declared inside a sub-block, the internal declaration temporarily replaces the external definition! 10

Example Scope Hole { int i; int j=7; Scope of outside j for (i=0; i<3; i++) { } int j=i+1; printf( j=%d\n,j); } printf( j=%d\n,j); Scope of inside j (Hole for outside j) j=1 j=2 j=3 j=7 11

Variable Class Automatic Created/Initialized on entry to block Destroyed on exit from block Static Created/Initialized when program starts Destroyed when program ends 12

Default Class Function/Block Variables are automatic Created/Initialized on entry to that function/block Deleted when that function/block ends Global Variables are Static Created/Initialized when the program starts Deleted when the program ends Automatic has no meaning! 13

Local Static Variables We can specify static keyword in a declaration Implies variable is created when program starts, deleted when program ends Does NOT mean that the scope is global!!!! Scope is still within that function 14

Example Local Static char * flipflop() { static int flip=1; if (flip) { flip=0; return flip ; } else { flip=1; return flop ; } } for(i=0;i<8;i++) printf( %s,flipflop()); flip flop flip flop flip flop flip flop 15

BAD FORM : Pseudo-Globals It is legal in C to nest a function inside another function This allows the variables in the outside function to be visible (in scope) for the inside function C Coders frown on this practice! Nested functions have other complications Nested functions cannot be re-used It s ugly and confusing 16

Example Nested Functions int main(int argc, char **argv) { char firstargletter(int i) { return argv[i][0]; } int j; for(j=0;j<argc;j++) printf( Arg start: %c\n, firstargletter(j)); return 0; } 17

Enumerations 18

Suppose I have 3 colors of paint RED GREEN BLUE 19

How do I represent these colors in C? I could put the color name in a string char can1[6]; strcpy(can1, green ); if (0==strcmp(can1, red )) printf( First can is red paint ); Takes lots of space Not very clear what is going on 20

How do I represent these colors in C? I could use the first letter R/G/B char can1; can1= G ; if (can1== R ) printf ( First can is red paint ); Takes less space Not very clear what is going on what if I have Grey and Black? 21

How do I represent these colors in C? I could use a number->color mapping 0=red, 1=green, 2=blue char can1; can1=1; if (can1==0) printf ( First can is red paint ); Takes less space Not very clear what is going on was green 2 or 3? 22

C has Enumerations Special C construct to make code clear An enumeration is any finite list of items enum colors { red, green, blue }; 23

C Enumeration Definition Defines a new data type Defines constant values of that type enum colors { red, green, blue }; Define a new type called enum colors Define 3 constants of type enum colors with anonymous values 24

Enumeration Constants Enumeration constants are variable names Cannot use these names for anything else int red=16; 25

C Enumeration Declaration Create a variable with an enumerated type enum colors can1; Type specification enum colors must be defined above Variable name Variable can have any value as long as it s a color enumeration constant. can1=green; 26

Putting it all together enum colors {red, green, blue} can1; can1=green; if (can1==red) printf( First can is red paint ); 27

Why enums? Makes reading the code crystal clear Compiler can check to make sure everything is correct can1=orange; // compiler error orange not a valid color Space efficient Easy to extend 28

Problem: Using enums in messages printf( The value of can1 is %d,can1); The value of can1 is 5 Problem enum values don t really make sense to people! 29

Solution: Provide a function to translate char * colorname(enum colors inc) { switch(inc) { case red : return red ; case green: return green ; case blue: return blue ; } return unknown ; } 30

Printing with a translator function printf( First can has %s paint\n,colorname(can1)); First can has green paint Note update translator function when enum changes! 31

Typedefs 32

Defining New Types Built in types: char, int, float, short int, long int, double, etc. Arrays extended types Pointers extended types Derived types: structures, enums, unions Must include struct lnode or union val_union 33

Derived Types can get Complicated struct lnode* nodelist[10]; nodelist is an array of 10 pointers to lnode structures union val_union **vptrs; vptrs is a pointer to one or more pointers to one or more instances of a val_union union 34

Anatomy of a Typedef typedef struct lnode * nodeptr; Built-In or Derived Type Name New Type Name (Synonym) 35

TypeDef Synonym for Any Type typedef struct lnode * nodeptr; nodeptr head; nodeptr newnode=makelnode(12); 36

Why TypeDef 1. Makes code much more readable It s much clearer to read an write nodeptr than struct lnode * 2. Encapsulate specific sub-types typedef float length_t; length_t atob; length_t btoc; Make this double to change all lengths! 37

Resources Programming in C, Chapter 7 Wikipedia Variable https://en.wikipedia.org/wiki/variable_(computer_science) Programming in C, Chapter 13 (Enumerated Data Types) Wikipedia Enumerated Type https://en.wikipedia.org/wiki/enumerated_type Enumeration Tutorial http://www.programiz.com/c-programming/cenumeration Scope Tutorial http://www.tutorialspoint.com/cprogramming/c_scope_rules.htm Wikipedia Typedef https://en.wikipedia.org/wiki/typedef 38