Chapter 12 Variables and Operators

Similar documents
Chapter 12 Variables and Operators

Chapter 12 Variables and Operators

Chapter 12 Variables and Operators

COSC121: Computer Systems: Runtime Stack

Lecture 5: C programming

Introduction to C Part 1 HLL s and the Basic Syntax. (Ch11 & 12)

Information Science 1

UNIT- 3 Introduction to C++

Unit 3. Operators. School of Science and Technology INTRODUCTION

Lecture 3. More About C

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Operators. Java operators are classified into three categories:

Operators in C. Staff Incharge: S.Sasirekha

Declaration and Memory

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

Chapter 3: Operators, Expressions and Type Conversion

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Operators & Expressions

Scope: Global and Local. Concept of Scope of Variable

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Chapter 14 Functions. Function. Example of High-Level Structure. Functions in C

Lexical Considerations

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Lecture 3 Tao Wang 1

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

A flow chart is a graphical or symbolic representation of a process.

Expressions and Precedence. Last updated 12/10/18

Information Science 1

BITG 1233: Introduction to C++

Arithmetic Operators. Portability: Printing Numbers

SECTION II: LANGUAGE BASICS

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Chapter 2: Basic Elements of C++

Full file at

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Objectives. In this chapter, you will:

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Variables and literals

1 Lexical Considerations

Computers Programming Course 6. Iulian Năstac

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

Chapter 2 Elementary Programming

ARG! Language Reference Manual

Work relative to other classes

Quick Reference Guide

Chapter 3 Structure of a C Program

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Programming I Lecture 7

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

JAVA Programming Fundamentals

Expression and Operator

Basics of Java Programming

Fundamental of Programming (C)

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

JAVA OPERATORS GENERAL

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Quick Reference Guide

LECTURE 3 C++ Basics Part 2

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Lexical Considerations

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basics of Programming

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

The C++ Language. Arizona State University 1

Operators. Lecture 3 COP 3014 Spring January 16, 2018

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

CS313D: ADVANCED PROGRAMMING LANGUAGE

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

DaMPL. Language Reference Manual. Henrique Grando

Reserved Words and Identifiers

Programming for Engineers Iteration

The pixelman Language Reference Manual. Anthony Chan, Teresa Choe, Gabriel Kramer-Garcia, Brian Tsau

Informatics Ingeniería en Electrónica y Automática Industrial

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Chapter 4: Expressions. Chapter 4. Expressions. Copyright 2008 W. W. Norton & Company. All rights reserved.

Course Outline Introduction to C-Programming

.Net Technologies. Components of.net Framework

CMPT 125: Lecture 3 Data and Expressions

Chapter 2. Lexical Elements & Operators

3. Java - Language Constructs I

Maciej Sobieraj. Lecture 1

Transcription:

Chapter 12 Variables and Operators

Highlights (1) r. height width operator area = 3.14 * r *r + width * height literal/constant variable expression (assignment) statement 12-2

Highlights (2) r. height width area = 3.14 * r *r + width * height Precedence: 우선순위 area = 3.14 * r *r + (width * height) Associativity: 결합법칙 area = ((3.14 * r) *r) + width * height also need to distinguish value (from evaluating an expression on the right-hand side) from action (assignment of a value to a variable on the left-hand side) 12-3

Basic C Elements Variable holds a value upon which a program acts has a type (integer, floating-point, character, etc) is an abstraction (i.e., symbolic name) of a memory location but its value is moved to a register when subject to an operation and moved back to memory when registers are full Operators predefined actions performed on data values combined with variables and constants (literals) to form expressions Is an abstraction of arithmetic / logic instructions 12-4

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

Variable Declaration Syntax int <variable name list>; double <variable name list>; char <variable name list>; Examples int score; int double char score, sum; area, volumn; InputChar; int sum = 0; 12-6

Variable Name (i.e., identifier) 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 meaningful 12-7

Examples Legal i wordspersecond same identifier words_per_second _green areally_longname_morethan31chars areally_longname_morethan31characters Illegal 10sdigit ten'sdigit done? double reserved keyword 12-8

Literals (i.e., constants) Integer 123 /* decimal */ -123 Floating point 6.023 Character 'c' 0x123 /* hexadecimal */ 6.023e23 /* 6.023 x 10 23 */ 5E12 /* 5.0 x 10 12 */ '\n' /* newline (more on Page 567 */ '\xa' /* ASCII 10 hexadecimal */ '\012' /* ASCII 10 octal */ 12-9

Scope: Global and Local Where is the variable accessible? Global: accessed anywhere in program Local: only accessible in a particular region 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 12-10

Example #include <stdio.h> int itsglobal = 0; block defined by open and closed braces { } 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 12-11

Operators Programmers manipulate values (ones stored in variables, literals/constants and, return values from functions) using the operators provided by the high-level language. Variables, constants, and operators combine to form an expression, which yields a value Each operator may correspond to many machine instructions. Example: The multiply operator (*) typically requires multiple LC-3 ADD instructions. 12-12

Expression Any combination of variables, literals/constants, operators, and function calls (i.e., their return values) that yield to a value every expression has a type (integer, floating-point, character, boolean) derived from the types of its components (according to rules defined in the C programming language) Examples: 3.14 width width*height 3.14*r*r + width*height counter >= STOP x + sqrt(y) x & z + 3 9 - w-- % 6 12-13

Statement Expresses a complete unit of work executed in sequential order Simple statement ends with semicolon z = x * y; y = y + 1; ; /* null statement */ Compound statement groups simple statements using braces (why needed?). syntactically equivalent to a simple statement { z = x * y; y = y + 1; } 12-14

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 (+) (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 12-15

Assignment Statement (action) Changes the value of a variable. x = x + 4; 1. Evaluate the expression on the right-hand side. 2. Set value of the left-hand side variable to result. 12-16

Assignment Operator (value) unique in C All expressions evaluate to a value, even ones with the assignment operator. For assignment, the result is the value assigned. the value of the right-hand side the value of expression y = x + 3 is the current value of variable x plus 3 Assignment associates right to left. y = x = 3; is equivalent to y = (x = 3); y gets the value 3, because (x = 3) evaluates to the value 3. 12-17

Arithmetic Operators Symbol Operation Usage Precedence Assoc * multiply x * y 6 l-to-r / divide x / y 6 l-to-r % modulo x % y 6 l-to-r + addition x + y 7 l-to-r - subtraction x - y 7 l-to-r All associate left to right. / % have higher precedence than + -. Operate on values -- neither operand is changed. 12-18

Arithmetic Expressions If mixed types, smaller type is "promoted" to larger. x + 4.3 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 1.666666...) Modulo -- result is remainder. x % 3 if x is int and x=5, result is 2. 12-19

Bitwise Operators Symbol Operation Usage Precedence Assoc ~ bitwise NOT ~x 4 r-to-l << left shift x << y 8 l-to-r >> right shift x >> y 8 l-to-r & bitwise AND x & y 11 l-to-r ^ bitwise XOR x ^ y 12 l-to-r bitwise OR x y 13 l-to-r Operate on variables bit-by-bit. Like LC-3 AND and NOT instructions. 12-20

Relational Operators Symbol Operation Usage Precedence Assoc > greater than x > y 9 l-to-r >= greater than or equal x >= y 9 l-to-r < less than x < y 9 l-to-r <= less than or equal x <= y 9 l-to-r == equal x == y 10 l-to-r!= not equal x!= y 10 l-to-r Result is 1 (TRUE) or 0 (FALSE): boolean type Note: Don't confuse equality (==) with assignment (=). 12-21

Logical Operators Symbol Operation Usage Precedence Assoc! logical NOT!x 4 r-to-l && logical AND x && y 14 l-to-r logical OR x y 15 l-to-r Treats the operands as boolean type: TRUE (non-zero) or FALSE (zero). Result is 1 (TRUE) or 0 (FALSE): boolean type 12-22

Special Operators: ++ and -- (unique in C) Changes value of variable after (or before) its value is used in an expression. Symbol Operation Usage Precedence Assoc ++ postincrement x++ 2 r-to-l -- postdecrement x-- 2 r-to-l ++ preincrement ++x 3 r-to-l -- predecrement --x 3 r-to-l Pre: Increment/decrement variable before using its value. Post: Increment/decrement variable after using its value. 12-23

Using ++ and -- x = 4; y = x++; Results: x = 5, y = 4 (because x is incremented after using its value) x = 4; y = ++x; Results: x = 5, y = 5 (because x is incremented before using its value) 12-24

Special Operators: +=, *=, etc. (unique in C) Arithmetic and bitwise operators can be combined with assignment operator. Statement Equivalent 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. 12-25

Special Operator: Conditional Symbol Operation Usage Precedence Assoc?: conditional x?y:z 16 l-to-r If x is TRUE (non-zero), result is y; else, result is z. Like a MUX, with x as the select signal. y z 1 0 x 12-26

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 might not have memorized precedence table. 12-27

Summary: Operator Precedence and Associativity Precedence Associativity Operators 1 (highest) l(eft) to r(ight) () (function call) [ ] (array index). -> 2 r(ight) to l(eft) ++ - - (postfix versions) 3 r to l ++ - - (prefix versions) 4 r to l * (indirection) & (address of) + (unary) - (unary) ~ (logical NOT)! (bitwise NOT) sizeof 5 r to l (type) (type cast) 6 l to r * (multiplication) / % 7 l to r + (addition) - (subtraction) 8 l to r << >> (shifts) 9 l to r < > <= >= (relational operators) 10 l to r ==!= (equality/inequality operators) 11 l to r & (bitwise AND) 12 l to r ^ (bitwise exclusive OR) 13 l to r (bitwise OR) 14 l to r && (logical AND) 15 l to r (logical OR) 16 l to r?: (conditional expression) 17 (lowest) r to l = += -= *= etc. (assignment operators) 12-28

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 Scope Name Type Offset Scope amount hours minutes rate seconds time int int int int int int 0-3 -4-1 -5-2 main main main main main main 12-29

Local Variable Storage Local variables are stored in user stack called an activation record, also known as a stack frame. Symbol table offset gives 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 function is called or a block is entered. Because stack grows downward, R5 contains the highest address of the frame, and variable offsets are <= 0. R5 #include <stdio.h> int main() { int amount; int rate; int time; int hours; int minutes; int seconds; seconds minutes hours time rate amount 12-30

Allocating Space for Variables 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 0x0000 0xFFFF instructions global data run-time stack PC R4 R6 R5 12-31

Variables and Memory Locations 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. Why? 12-32

Example: Compiling to LC-3 #include <stdio.h> 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); 12-33

Example: Symbol Table Name Type Offset Scope inglobal int 0(R4) global inlocal int 0(R5) local:main outlocala int -1(R5) local:main outlocalb int -2(R5) local:main 12-34

Example: Code Generation ; 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) 12-35

Example (continued) ; first statement: ; outlocala = inlocal & ~inglobal; LDR R0, R5, #0 ; get inlocal 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) 12-36

Example (continued) ; next statement: ; outlocalb = (inlocal + inglobal) ; - (inlocal - inglobal); LDR R0, R5, #0 ; inlocal LDR R1, R4, #0 ; inglobal ADD R0, R0, R1 ; R0 contains LDR R2, R5, #0 ; inlocal LDR R3, R4, #0 ; inglobal NOT R3, R3 ADD R3, R3, #1 ADD R2, R2, R3 ; R2 contains (inlocal + inglobal) (inlocal - inglobal) NOT R2, R2 ; negate ADD R2, R2, #1 ADD R0, R0, R2 ; (inlocal + inglobal) - inlocal - inglobal) STR R0, R5, #-2 ; outlocalb (offset = -2) 12-37

꼭기억해야할것 variable type scope operator precedence associativity literal/constant expression yields a value after being evaluated has a type statement 11-38