Homework Starting Chapter 2 K&R. Read ahead. Questions?

Slides:



Advertisements
Similar presentations
Modular Programming With Functions
Advertisements

Homework Starting Chapter 2 K&R. Read ahead. Questions?
1 Homework Turn in HW2 at start of next class. Starting Chapter 2 K&R. Read ahead. HW3 is on line. –Due: class 9, but a lot to do! –You may want to get.
Structure of a C program
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
CS1061 C Programming Lecture 4: Indentifiers and Integers A.O’Riordan, 2004.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
C Programming for Embedded Systems. fig_06_00 Computer Layers Low-level hardware to high-level software (4GL: “domain-specific”, report-driven, e.g.)
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
IT253: Computer Organization
C Tokens Identifiers Keywords Constants Operators Special symbols.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
CPS120: Introduction to Computer Science
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Copyright Curt Hill Variables What are they? Why do we need them?
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
Starting Chapter 2 K&R. Read ahead.. Call by Value vs Call by Reference Simple variables passed as function parameters in C are actually only copies on.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Numbers in ‘C’ Two general categories: Integers Floats
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
The Machine Model Memory
Chapter 7: User-Defined Functions II
A bit of C programming Lecture 3 Uli Raich.
Chapter 12 Variables and Operators
Chap. 2. Types, Operators, and Expressions
Loading a Single Byte There are two instructions that load a byte from a memory address. The instructions differ in how the 8-bit byte is put into the.
ECE Application Programming
Tokens in C Keywords Identifiers Constants
COM S 326X Deep C Programming for the 21st Century Prof. Rozier
ICS103 Programming in C Lecture 3: Introduction to C (2)
EPSII 59:006 Spring 2004.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
C Short Overview Lembit Jürimägi.
Instructor: Ioannis A. Vetsikas
User-Defined Functions
Chapter 2 - Data Types and Storage Classes
Chapter 12 Variables and Operators
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
CMSC 104, Section 4 Richard Chang
Introduction to Abstract Data Types
CS 240 – Lecture 5 Scope of Variables, The Stack, Automatic Variables, Global Variables, Constant Type.
Lectures on Numerical Methods
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Homework Homework Continue Reading K&R Chapter 2 Questions?
Your questions from last session
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Homework Reading Programming Assignments Finish K&R Chapter 1
WEEK-2.
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
The C Language: Intro.
Variables in C Topics Naming Variables Declaring Variables
C Language B. DHIVYA 17PCA140 II MCA.
Variables in C Topics Naming Variables Declaring Variables
EECE.2160 ECE Application Programming
Variables in C Topics Naming Variables Declaring Variables
Functions that return a value
Variables in C Topics Naming Variables Declaring Variables
Presentation transcript:

Homework Starting Chapter 2 K&R. Read ahead. Questions?

Call by Value vs Call by Reference Simple variables passed as function parameters in C are actually only copies on the stack. (Note: Stack pointer is a register) foo(i, j); void foo(int i, int j) { } Stack Data Unused Stack Pointer Before call and after return Copy of Value The input variable will never change The function works on the copy of that variable Return Data Stack Data Unused i j Stack Pointer After call and before return

Call by Value vs Call by Reference This is known as Call by Value. Unlike some languages, which have call by reference You can't change arguments in original location within the function -- just change the stack copy To make changes, you must pass pointers to original variables. See next slide. You’re not responsible for pointers yet, but start getting used to them!

Pointers as Arguments Pointer variables passed as function parameters in C are still only value on the stack but can be used to access original location indirectly foo(&i, &j); void foo(int *i, int *j) { } Stack Data Unused Stack Pointer Before call and after return Show the differences of call by value and reference on memory map Point to values Return Data Stack Data Unused &i &j Stack Pointer After call and before return

Pointers as Arguments The following doesn’t work!!! void exchgint (int a, int b) { int dummy; dummy = a; a = b; b = dummy; } Data got exchanged in temporary variables

Pointers as Arguments Must be done with pointers!!! void exchgint (int *pa, int *pb) { int dummy; dummy = *pa; *pa = *pb; *pb = dummy; } Dereferencing

Pointers as Arguments An array name is automatically passed as a pointer You don't need to create a pointer yourself with the “address of” operator (&) int array1[10], array2[10]; foo(array1, array2); Unless you are passing a pointer to a specific array element (Remember printf in visitype?) foo(&array1[4*i], &array2[4*j]);

Scope of Variables – Local Automatic Each local variable of a function (inside { }) comes into existence only when it is called disappears when a return is performed. Local variables are said to be automatic. Memory is allocated on the stack after the calling sequence argument values Undefined (i.e. garbage) value unless explicitly initialized in the source code Initialization is done each time the function or block is entered (K&R P.85). Show an example Local Variables Return Data Stack Data Unused i j Stack Pointer After local variables are allocated

Scope of Variables – Local Static A local alternative to automatic is known as static. A static variable declared in a function is preserved in memory. Still local - can only be used inside { }. It is guaranteed to be initialized to zero if it is not initialized otherwise. If the static variable is initialized, it is done once before the program starts execution (K&R P.85). e.g., the seed of a random number generator so it will have memory from one invocation to the next and not always give the same random number. int rand( ){ static int seed = 1; /* initialize to 1 in the beginning and … remember value between calls to rand */ }

Scope of Variables – Local Static Good for implementing a “Finite State Machine” They allow a function to preserve its state value(s) But, be careful using local static variables!! A function may behave differently when it is called with different values preserved in local static variables Makes testing of a function more complex because you need to test its behavior with all possible values of any local static variables Complex sequence of calls to function may be required to drive local static variables into desired test “state(s)” Good thing -> you want to save a variable during many calls You want to save previous state Your current state depends on the previous value. And if you don’t know what the previous value is, you can not debug your code and repeat that experiment to see the failure situation

Scope of Variables - External Alternative to local is known as external Look at maxline program on page 32 of K&R Variables declared ahead of/outside of all { }’s are available to all functions within the program load These are sometimes called “global variables” Can be used to pass data between functions Values are preserved like static local variables It is guaranteed to be initialized to zero If the external variable is initialized, it is done once before the program starts execution. Not a good idea to use them – Why not? You can use the external variables anywhere in your code Not good because suppose you have many functions and in some of them you use external variables. So these functions can manipulate these variables and you don’t know that

Scope of Variables - External Global variables are not a good idea because: They can be accessed from anywhere. If their value gets corrupted, it is NOT easy to figure out what code in which function caused the corruption. They make the functions dependent on their external environment instead of being able to stand alone using arguments to get their input values and a return value to pass back an output value. Software architecture/design standards for most projects will prohibit use of “global variables” or severely restrict their use. Don’t use them!!

Scope of Variables – External Static Another alternative known as external static No good examples that I see in K&R Static variables declared ahead of/outside of all { }’s are available to all functions within this file only These are very similar to OOP “class variables” Can be used to pass data between functions in file only Values are preserved like static local variables It is guaranteed to be initialized to zero If the external static variable is initialized, it is done once before the program starts execution. These are more acceptable than global variables

Examples of Scopes of Variables These examples are from p.342: “C Programming for Scientists and Engineers with Applications” by Rama Reddy and Carol Ziegler, Jones and Bartlett 2010.

Scope of Variables – Example #1 #include <stdio.h> int main(){ int a=10; printf(“a=%d\n”, a); { int b=5; printf(“b=%d\n”, b); int c=40; printf(“c=%d\n”,c); } return 0; 10 5 Scope of a Scope of b Scope of c 40

Scope of Variables – Example #2 #include <stdio.h> int main(){ int x=10; printf(“x=%d\n”, x); { int x=5; int x=40; printf(“x=%d\n”,x); } x=x+4; x=x+15; return 0; 10 If the same variable is defined inside and outside the block, the name inside the block will be referenced if the block is being executed. 5 40 x=40 x=5+4 x=10+15 9 25

Scope of Variables – Example #3 int x; void func1(void){ x=5; printf(“In func1 x=%d\n”,x); return; } void func2(void){ int x=0; printf(“In func2 x=%d\n”, x); void func3(void){ printf(“In func3 x=%d\n”, x); return ; #include <stdio.h> void func1(void); void func2(void); void func3(void); int main(){ int x=20; printf(“x=%d\n”, x); func1(); x=x+10; func2(); x=x+40; printf(“x=%d\n”,x); func3(); return 0; } 5 20 30 Scope of 2nd x Scope of 3rd x Scope of 1st x 70 5

Scope of Variables – Example #4 #include <stdio.h> void func1(void); void func2(void); int main(){ int x=5; printf(“x=%d\n”, x); func1(); x=x+5; func2(); printf(“x=%d\n”,x); return 0; } 5 10 Scope of x 15 int x; void func1(void){ x=6; printf(“In func1 x=%d\n”,x); } void func2(void){ x=x+10; printf(“In func2 x=%d\n”, x); External storage class definition 6 Scope of x 16

Scope of Variables – Example #5 #include <stdio.h> void func1(void); void func2(void); int main(){ extern int x; x=1; printf(“x=%d\n”, x); func1(); x=x+6; func2(); x=x+7; printf(“x=%d\n”,x); return 0; } 1 11 28 Scope of x File 1 Gcc –m32 file1.c file2.c –o file The storage is defined somewhere else, it just matches them up. The compiler understands that it’s outside of this scope and it will find it. A global variable int x; void func1(void){ printf(“In func1 x=%d\n”,x); x=5; } void func2(void){ x=x+10; printf(“In func2 x=%d\n”, x); 1 File 2 21

Scope of Variables – Example #6 #include <stdio.h> void func1(void); void func2(void); int main(){ extern int x; x=1; printf(“x=%d\n”, x); func1(); x=x+6; func2(); x=x+7; printf(“x=%d\n”,x); return 0; } 1 11 Scope of x File 2 18 int x; void func1(void){ x=5; printf(“In func1 x=%d\n”,x); } void func2(void){ int x=10; printf(“In func2 x=%d\n”, x); Advantage of using global variable -> you don’t need to pass the variable to func1 5 File 1 10 Scope of x

Data Types Finished K&R Chapter 1 / Now starting Chapter 2 Variable Names Data Types: char int short int long int float double

Variable / Symbolic Constant Names Rules for generating names: All letters and digits are allowed Uppercase and lower case letters are different First character must be a letter Underscore _ counts as a letter (useful for improving readability) But, don’t begin variable names with _ (reserved for library routines) Some operating system variables start with _

Variable / Symbolic Constant Names (cont’d) Rules for generating names: Internal - at least 31 characters are significant External – e.g. function names: only count on 6 characters Avoid using C keywords (if, else, int, float, etc.) Choose variable names that are related to the purpose or use of the variable Use meaningful names

Data Types char (character) char has 8 bits (stored in one byte in memory) unsigned: 0 ≤ char ≤ 28 -1 00000000 ≤ char ≤ 11111111 Overflow at 255 (255 + 1 = 0) Underflow at 0 (0 – 1 = 255) signed (if supported in the implementation): -27 ≤ char ≤ 27-1 10000000 ≤ char ≤ 01111111 Overflow at 127 (127 + 1 = -128) Underflow at –128 (-128 – 1 = 127) Sign bit -> the most significant bit. 0 positive. 1 negative. Show 8 bits on the board Largest + 1 -> carry bit Default -> signed

Data Types int (integer on our machines) int has 32 bits (stored in four sequential bytes in memory) unsigned: 0 ≤ char ≤ 232 - 1 0x00000000 ≤ char ≤ 0xffffffff Overflow at 4294967295 (4294967295 + 1 = 0) Underflow at 0 (0 – 1 = 4294967295) signed: -231 ≤ char ≤ 231-1 0x80000000 ≤ char ≤ 0x7fffffff Overflow at 2147483647 (2147483647 + 1 = –2147483648) Underflow at –2147483648 (-2147483648 – 1 = 2147483647)

Data Types short int (short integer on our machines) short int has 16 bits (stored in two sequential bytes in memory) unsigned: 0 ≤ char ≤ 216 - 1 0x0000 ≤ char ≤ 0xffff Overflow at 65535 (65535 + 1 = 0) Underflow at 0 (0 – 1 = 65535) signed: -215 ≤ char ≤ 215-1 0x8000 ≤ char ≤ 0x7fff Overflow at 32767 (32767 + 1 = –32768) Underflow at –32768 (-32768 – 1 = 32767)

Data Types long int (long integer on our machines – same as int) long int has 32 bits (stored in four sequential bytes in memory) unsigned: 0 ≤ char ≤ 232 - 1 0x0000 0000 ≤ char ≤ 0xffff ffff Overflow at 4294967295 (4294967295 + 1 = 0) Underflow at 0 (0 – 1 = 4294967295) signed: -231 ≤ char ≤ 231-1 0x8000 0000 ≤ char ≤ 0x7fff ffff Overflow at 2147483647 (2147483647 + 1 = –2147483648) Underflow at –2147483648 (-2147483648 – 1 = 2147483647) 64bit os -> 64bits for long int So because of that I told you to use –m32, there would be no confusion about this To show hexadecimal -> 0x . . .

Data Types float 32-bits (stored in four sequential bytes in memory) based on the IEEE 754 floating point standard + 1.f x 2e Show a number in int and float. For example 12 1 8 bits 23 bits sign exponent e fraction f

Data Types float, double Both represent numbers with fractional parts “double” is a “float” with more precision Don't do much with float or double in this course Implementation is machine dependent: for our machine: float is 4 bytes double is 8 bytes Without a co-processor to do floating point computations, it takes a lot of computation time to do them in software. Not often used in real time, embedded systems. A cost versus performance tradeoff!

Numbering Systems Binary (no symbol to represent binary numbers) Octal (Octal Constant is written 0dd…) OCTAL BINARY OCTAL BINARY 0 000 4 100 1 001 5 101 2 010 6 110 3 011 7 111 Note: Can’t write a decimal value with a leading 0 digit – will be interpreted as octal zero Int i=014; Int i=0xc; Int i=12;

Numbering Systems Hex (Hex Constant is written 0xdd…) HEX BIN. HEX BIN. HEX BIN. HEX BIN. 0 0000 4 0100 8 1000 C 1100 1 0001 5 0101 9 1001 D 1101 2 0010 6 0110 A 1010 E 1110 3 0011 7 0111 B 1011 F 1111 NOTE: Memorize these translations DO NOT convert between binary and Hex or Octal by converting to decimal and back! Much harder!! Learn to group binary digits by 3 (for octal) or 4 (for hex) to convert

Examples of the Number System Decimal Octal Hex 31 --------> 037 -----------> 0x1f 128 -------->0200 ----------> 0x80 Show the conversion on the board! Write them in binary form and group them

Numbering Systems char Data Type Constants ‘a’ integer value in ASCII code for letter a ‘0’ integer value in ASCII code for number 0 ‘\b’ integer value in ASCII code for backspace ‘\ooo’ octal value 000 – 377 (0 – 255 decimal) ‘\xhh’ hex value 0x00 – 0xff (0 – 255 decimal) examples ‘a’ = 0x61 ‘0’ = 0x30 ‘\127’ = 0x57 ‘\x2b’ = 0x2b

Numbering Systems Other Data Type Constants 1234 int 1234L long int 1234UL unsigned long int 1234. double (because of decimal point) 1234.4F float (because of the suffix) 1234e-2 double (because of exponent) To specify what type of variable you are using