CMPE13Cyrus Bazeghi 1 Chapter 12 Variables and Operators.

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12.
Chapter 11-14, Appendix D C Programs Higher Level languages Compilers C programming Converting C to Machine Code C Compiler for LC-3 Please return breadboards.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
Overview C programming Environment C Global Variables C Local Variables Memory Map for a C Function C Activation Records Example Compilation.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.2 Expressions and Assignment Statement.
Chapter 11-12, Appendix D C Programs Higher Level languages Compilers C programming Converting C to Machine Code C Compiler for LC-3.
Chapter 2 Data Types, Declarations, and Displays
C Stack Frames / Pointer variables Stack: Local Variables Pass & Return values Frame Ptr linkage (R5) and PC linkage (R7) Pointer Variables: Defining &
Basic Elements of C++ Chapter 2.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 12 Variables and Operators. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Basic C Elements.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 11 Programming in C Compilation vs. Interpretation Different ways of translating high-level language Compilation translates code into machine.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 11 Introduction to Programming in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Compilation.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CSC 107 – Programming For Science. Announcements  Memorization is not important, but…  … you will all still be responsible for information  Instead.
CPS120: Introduction to Computer Science Operations Lecture 9.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
CSC 107 – Programming For Science. The Week’s Goal.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Chapter 12 Variables and Operators. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Basic C Elements.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Types of C Variables:  The following are some types of C variables on the basis of constants values it has. For example: ○ An integer variable can hold.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Module B - Computation1/61 Module-B-Computation Variables Basic Memory Operations Expressions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
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.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU Status 6/10/2016 Initial content copied verbatim from ECE 103 material developed.
Chapter Topics The Basics of a C++ Program Data Types
Chapter 12 Variables and Operators
BASIC ELEMENTS OF A COMPUTER PROGRAM
INSPIRING CREATIVE AND INNOVATIVE MINDS
Tokens in C Keywords Identifiers Constants
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
ITEC113 Algorithms and Programming Techniques
Basic Elements of C++.
Chapter 12 Variables and Operators
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Introduction to C Programming
Basic Elements of C++ Chapter 2.
Chapter 12 Variables and Operators
Chapter 12 Variables and Operators
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Introduction to C Programming
Lectures on Numerical Methods
Expressions and Assignment
Primitive Types and Expressions
Chapter 11 Programming in C
Introduction to C Programming
Chapter 12 Variables and Operators
Presentation transcript:

CMPE13Cyrus Bazeghi 1 Chapter 12 Variables and Operators

CMPE13Cyrus Bazeghi 2 Basic C Elements Variables –named, typed data items Operators –predefined actions performed on data items –combined with variables to form expressions, statements Rules and usage Implementation using LC-3

CMPE13Cyrus Bazeghi 3 Data Types C for the LC-3 has three basic data types int integer (at least 16 bits) double floating point (at least 32 bits) char character (at least 8 bits) Exact size can vary, depending on processor –int is supposed to be "natural" integer size; for LC-3, that's 16 bits bits for most modern processors

CMPE13Cyrus Bazeghi “Standard” Data Types 4 TypeBytesRange short int2-32,768 -> +32,767 (32kb) unsigned short int20 -> +65,535 (64Kb) unsigned int40 -> +4,294,967,295 ( 4Gb) int4-2,147,483,648 -> +2,147,483,647 ( 2Gb) long int4-2,147,483,648 -> +2,147,483,647 ( 2Gb) signed char > +127 unsigned char10 -> +255 float4Big double8Bigger long double12Biggest

CMPE13Cyrus Bazeghi 5 Variable Names Any combination of letters, numbers, and underscore (_) Case matters –"sum" is different than "Sum" Cannot begin with a number –usually, variables beginning with underscore are used only in special library routines Only first 31 characters are used

CMPE13Cyrus Bazeghi 6 Examples Legal i wordsPerSecond words_per_second _green aReally_longName_moreThan31chars aReally_longName_moreThan31characters Illegal 10sdigit ten'sdigit done? double reserved keyword same identifier

CMPE13Cyrus Bazeghi 7 Literals Integer 123 /* decimal */ x123 /* hexadecimal */ Floating point e23 /* x */ 5E12 /* 5.0 x */

CMPE13Cyrus Bazeghi 8 Literals Character 'c' '\n' /* newline */ '\xA' /* ASCII 10 (0xA) */

CMPE13Cyrus Bazeghi 9 Scope: Global and Local Where is the variable accessible? Global: accessed anywhere in program Local: only accessible in a particular region

CMPE13Cyrus Bazeghi 10 Scope: Global and Local Compiler infers scope from where variable is declared –programmer doesn't have to explicitly state Variable is local to the block in which it is declared –block defined by open and closed braces { } –can access variable declared in any "containing" block Global variable is declared outside all blocks

CMPE13Cyrus Bazeghi 11 Structure of a C program One main() function A bunch of other functions /*****************************/ main() { } /* */ functionA() { } /* */ functionB() { } /*****************************/

CMPE13Cyrus Bazeghi 12 Example #include int itsGlobal = 0; main() { int itsLocal = 1; /* local to main */ printf("Global %d Local %d\n", itsGlobal, itsLocal); { int itsLocal = 2; /* local to this block */ itsGlobal = 4; /* change global variable */ printf("Global %d Local %d\n", itsGlobal, itsLocal); } printf("Global %d Local %d\n", itsGlobal, itsLocal); } Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 1

CMPE13Cyrus Bazeghi 13 Operators Programmers manipulate variables using the operators provided by the high-level language. Variables and operators combine to form expressions and statements which denote the work to be done by the program.

CMPE13Cyrus Bazeghi 14 Operators Each operator may correspond to many machine instructions. –Example: The multiply operator ( * ) typically requires multiple LC-3 ADD instructions.

CMPE13Cyrus Bazeghi 15 Expression Any combination of variables, constants, operators, and function calls –every expression has a type, derived from the types of its components (according to C typing rules) Examples: counter >= STOP x + sqrt(y) x & z + 3 || 9 - w-- % 6

CMPE13Cyrus Bazeghi 16 Statement Expresses a complete unit of work –executed in sequential order Simple statement ends with semicolon z = x * y; /* assign product to z */ y = y + 1; /* after multiplication */ ; /* null statement */

CMPE13Cyrus Bazeghi 17 Statement Compound statement groups simple statements using braces. –syntactically equivalent to a simple statement { z = x * y; y = y + 1; }

CMPE13Cyrus Bazeghi 18 Operators Three things to know about each operator (1) Function –what does it do? (2) Precedence –in which order are operators combined? –Example: "a * b + c * d" is the same as "(a * b) + (c * d)" because multiply (*) has a higher precedence than addition (+)

CMPE13Cyrus Bazeghi 19 Operators (3) Associativity –in which order are operators of the same precedence combined? –Example: "a - b - c" is the same as "(a - b) - c" because add/sub associate left-to-right

CMPE13Cyrus Bazeghi 20 Assignment Operator Changes the value of a variable. x = x + 4; 1. Evaluate right-hand side. 2. Set value of left-hand side variable to result.

CMPE13Cyrus Bazeghi 21 Assignment Operator All expressions evaluate to a value, even ones with the assignment operator. For assignment, the result is the value assigned. –usually (but not always) the value of the right-hand side type conversion might make assigned value different than computed value

CMPE13Cyrus Bazeghi 22 Assignment Operator Assignment associates right to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3.

CMPE13Cyrus Bazeghi 23 Arithmetic Operators All associate left to right. * / % have higher precedence than + -. SymbolOperationUsagePrecedenceAssoc *MultiplyX * Y6L-to-R /DivideX / Y6L-to-R %ModuloX % Y6L-to-R +AdditionX + Y7L-to-R -subtractionX - Y7L-to-R

CMPE13Cyrus Bazeghi Examples basic.c 24

CMPE13Cyrus Bazeghi 25 Arithmetic Expressions If mixed types, smaller type is "promoted" to larger. x if x is int, converted to double and result is double Integer division -- fraction is dropped. x / 3 if x is int and x=5, result is 1 (not )

CMPE13Cyrus Bazeghi 26 Arithmetic Expressions Modulo -- result is remainder. x % 3 if x is int and x=5, result is 2.

CMPE13Cyrus Bazeghi 27 Bitwise Operators Operate on variables bit-by-bit. –Like LC-3 AND and NOT instructions. Shift operations are logical (not arithmetic). Operate on values -- neither operand is changed. SymbolOperationUsagePrecedenceAssoc ~Bitwise NOT~X4R-to-L <<Left shiftX << Y8L-to-R >>Right shiftX >> Y8L-to-R &Bitwise ANDX & Y11L-to-R ^Bitwise XORX ^ Y12L-to-R |Bitwise ORX | Y13L-to-R

CMPE13Cyrus Bazeghi Examples bitwise.c 28

CMPE13Cyrus Bazeghi 29 Logical Operators Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero). Result is 1 (TRUE) or 0 (FALSE). SymbolOperationUsagePrecedenceAssoc !Logical NOT!X4R-to-L &&Logical ANDX && Y14L-to-R ||Logical ORX || Y15L-to-R

CMPE13Cyrus Bazeghi 30 Relational Operators Result is 1 (TRUE) or 0 (FALSE). Note: Don't confuse equality (==) with assignment (=). SymbolOperationUsagePreced ence Assoc >Greater thanX > Y9L-to-R >=Greater than or equalX >= Y9L-to-R <Less thanX < Y9L-to-R <=Less than or equalX <= Y9L-to-R ==EqualX == Y10L-to-R !=Not equalX != Y10L-to-R

CMPE13Cyrus Bazeghi 31 Special Operators: ++ and -- Changes value of variable before (or after) its value is used in an expression. Pre: Increment/decrement variable before using its value. Post: Increment/decrement variable after using its value. SymbolOperationUsagePrecedenceAssoc ++Post incrementX++2R-to-L --Post decrementX--2R-to-L ++Pre increment++X3R-to-L --Pre decrement--X3R-to-L

CMPE13Cyrus Bazeghi 32 Using ++ and -- x = 4; y = x++; Results: x = 5, y = 4 (because x is incremented after assignment) x = 4; y = ++x; Results: x = 5, y = 5 (because x is incremented before assignment)

CMPE13Cyrus Bazeghi 33 Practice with Precedence Assume a=1, b=2, c=3, d=4. x = a * b + c * d / 2; /* x = 8 */ same as: x = (a * b) + ((c * d) / 2); For long or confusing expressions, use parentheses, because reader (or you!) might not have memorized precedence table. Note: Assignment operator has lowest precedence, so all the arithmetic operations on the right-hand side are evaluated first.

CMPE13Cyrus Bazeghi 34 Special Operators: +=, *=, etc. Arithmetic and bitwise operators can be combined with assignment operator. StatementEquivalent assignment x += y;x = x + y; x -= y;x = x - y; x *= y;x = x * y; x /= y;x = x / y; x %= y;x = x % y; x &= y;x = x & y; x |= y;x = x | y; x ^= y;x = x ^ y; x <<= y;x = x << y; x >>= y;x = x >> y; All have same precedence and associativity as = and associate right-to-left.

CMPE13Cyrus Bazeghi 35 Special Operator: Conditional If x is TRUE (non-zero), result is y; else, result is z. Like a MUX, with x as the select signal. x y z 10 SymbolOperationUsagePrecedenceAssoc ?:ConditionalX ? Y : Z16L-to-R

CMPE13Cyrus Bazeghi 36 Special Operator: Conditional main () { int x, y, z; int result; x = 0; y = 5; z = 10; result = x ? y : z; printf ("%d\n",result); }

CMPE13Cyrus Bazeghi 37 Variable allocation Global variables – allocated on the HEAP Local variables – allocated in the activation record –For each block –For each function

CMPE13Cyrus Bazeghi 38 Memory map Global data section –All global variables stored here (actually all static variables) –R4 points to beginning Run-time stack –Used for local variables –R6 points to top of stack –R5 points to top frame on stack –New frame for each block (goes away when block exited) Offset = distance from beginning of storage area –Global: LDR R1, R4, #4 –Local: LDR R2, R5, #-3 user code global data (heap) run-time stack 0x0000 0xFFFF PC R4 R6 R5 system (res)

CMPE13Cyrus Bazeghi 39 Sample program Network rate calculation program

CMPE13Cyrus Bazeghi 40 Local variable storage Local variables are stored in an activation record, also known as a stack frame. Symbol table “offsets” give the distance from the base of the frame. –R5 is the frame pointer – holds address of the base of the current frame. –A new frame is pushed on the run-time stack each time a block is entered. –Because stack grows downward, base is the highest address of the frame, and variable offsets are <= 0. seconds minutes hours time rate amount R5 High Mem Low Mem R6

CMPE13Cyrus Bazeghi 41 Symbol table Like assembler, compiler needs to know information associated with identifiers In assembler, all identifiers were labels and information is address Compiler keeps more information Name (identifier) Type Location in memory (offset wrt frame ptr) Scope NameTypeOffset Scope amount hours minutes rate seconds time int main

CMPE13Cyrus Bazeghi 42 register variables In our examples, a variable is always stored in memory. When assigning to a variable, must store to memory location. A real compiler would perform code optimizations that try to keep variables allocated in registers. Programmer can try to suggest to the compiler which variables, using the modifier register

CMPE13Cyrus Bazeghi 43 Example: Compiling to LC-3 #include int inGlobal; main() { int inLocal; /* local to main */ int outLocalA; int outLocalB; /* initialize */ inLocal = 5; inGlobal = 3; /* perform calculations */ outLocalA = inLocal++ & ~inGlobal; outLocalB = (inLocal + inGlobal) - (inLocal - inGlobal); /* print results */ printf("The results are: outLocalA = %d, outLocalB = %d\n", outLocalA, outLocalB); }

CMPE13Cyrus Bazeghi 44 Example: Symbol table NameTypeOffsetScope inGlobalint0global inLocalint0main outLocalAintmain outLocalBint-2main

CMPE13Cyrus Bazeghi 45 Example: Code generation (1/3) ; main ; initialize variables AND R0, R0, #0 ADD R0, R0, #5 ; inLocal = 5 STR R0, R5, #0 ; (offset = 0) AND R0, R0, #0 ADD R0, R0, #3 ; inGlobal = 3 STR R0, R4, #0 ; (offset = 0)

CMPE13Cyrus Bazeghi 46 Example: Code generation (2/3) ; first statement: ; outLocalA = inLocal++ & ~inGlobal; LDR R0, R5, #0 ; get inLocal ADD R1, R0, #1 ; increment STR R1, R5, #0 ; store LDR R1, R4, #0 ; get inGlobal NOT R1, R1 ; ~inGlobal AND R2, R0, R1 ; inLocal & ~inGlobal STR R2, R5, #-1 ; store in outLocalA ; (offset = -1)

CMPE13Cyrus Bazeghi 47 Example: Code generation (3/3) ; next statement: ; outLocalB = (inLocal + inGlobal) ; - (inLocal - inGlobal); LDR R0, R5, #0 ; inLocal LDR R1, R4, #0 ; inGlobal ADD R0, R0, R1 ; R0 is sum LDR R2, R5, #0 ; inLocal LDR R3, R4, #0 ; inGlobal NOT R3, R3 ADD R3, R3, #1 ADD R2, R2, R3 ; R2 is difference NOT R2, R2 ; negate ADD R2, R2, #1 ADD R0, R0, R2 ; R0 = R0 - R2 STR R0, R5, #-2 ; outLocalB (offset = -2)