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

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

Lecture 5: C programming

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

Scope: Global and Local. Concept of Scope of Variable

UNIT- 3 Introduction to C++

Unit 3. Operators. School of Science and Technology INTRODUCTION

Information Science 1

n Address of a variable in memory n Allows us to indirectly access variables ! Array n A list of values arranged sequentially in memory

1 Lexical Considerations

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

Variables and literals

Lexical Considerations

Declaration and Memory

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

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Review Topics. parameter passing, memory model)

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

The Arithmetic Operators

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture 3. More About C

Chapter 11 Introduction to Programming in C

C++ Programming Basics

LECTURE 3 C++ Basics Part 2

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

Chapter 2 Elementary Programming

1/29/2018. Starting a Program Executes its main Function. ECE 220: Computer Systems & Programming. The Function main Divides into Two Parts

Full file at

Maciej Sobieraj. Lecture 1

Chapter 11 Introduction to Programming in C

Information Science 1

Work relative to other classes

Course Outline Introduction to C-Programming

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

Chapter 3: Operators, Expressions and Type Conversion

Objectives. In this chapter, you will:

Programming for Engineers Introduction to C

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

Arithmetic Expressions in C

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Lexical Considerations

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

Chapter 2: Basic Elements of C++

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

Basics of Java Programming

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

BASIC ELEMENTS OF A COMPUTER PROGRAM

JAVA Programming Fundamentals

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

Chapter 11 Introduction to Programming in C

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

Review Topics. Midterm Exam Review Slides

Lecture 3 Tao Wang 1

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

3. Java - Language Constructs I

Chapter 2 Bits, Data Types, and Operations

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Pointers and Arrays

CGS 3066: Spring 2015 JavaScript Reference

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Review Topics. Midterm Exam Review Slides

Chapter 11 Introduction to Programming in C

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

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

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

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

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

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

Quick Reference Guide

Problem Solving in C. Stepwise Refinement. ...but can stop refining at a higher level of abstraction. Same basic constructs. as covered in Chapter 6

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expression and Operator

ARG! Language Reference Manual

Programming for Engineers Iteration

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Decaf Language Reference

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

A Java program contains at least one class definition.

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

DaMPL. Language Reference Manual. Henrique Grando

Operators in C. Staff Incharge: S.Sasirekha

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

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

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Computer System and programming in C

Control Structures. Chapter 13 Control Structures. Example If Statements. ! Conditional. if (condition) action;

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

Add Subtract Multiply Divide

The C++ Language. Arizona State University 1

FRAC: Language Reference Manual

Full file at C How to Program, 6/e Multiple Choice Test Bank

Review Topics. Final Exam Review Slides

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Chapter 03: Computer Arithmetic. Lesson 09: Arithmetic using floating point numbers

Transcription:

Basic C Elements Chapter 12 Variables and Operators Original slides from Gregory Byrd, North Carolina State University! 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 instructions Modified slides by Chris Wilcox, Colorado State University 2 Data Types Variable Names! C has three basic data types eger (at least 16 bits) double floating po (at least 32 bits) char character (at least 8 bits)! Exact size can vary, depending on processor is supposed to be "natural" eger size, for LC-3 that's 16 bits, LC-3 does not have double on a modern processor is usually 32 bits, double is usually 64 bits! Any combination of letters, numbers, and underscore (_)! Case matters "sum" is different than "Sum, this is also true of function names! Cannot begin with a number usually variables beginning with underscore are used only in special library routines! Only first 31 characters are used actually that s compiler dependent, so be careful not to create ambiguous variables! 3 4 1

Examples! Legal i wordspersecond same identifier words_per_second _green areally_longname_morethan31chars areally_longname_morethan31characters! Illegal 10sdigit reserved keyword ten'sdigit done? double 5 Literals! Integer 123 /* decimal */ -123 0x123 /* hexadecimal */! Floating po 6.023 6.023e23 /* 6.023 x 10 23 */ 5E12 /* 5.0 x 10 12 */! Character 'c' '\n' /* newline */ '\xa' /* ASCII 10 (0xA) */ 6 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 in the program 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 variables are declared outside all blocks 7 #include <stdio.h> itsglobal = 0; Example () { itslocal = 1; /* local to */ prf("global %d Local %d\n", itsglobal, itslocal); { itslocal = 2; /* local to this block */ itsglobal = 4; /* change global variable */ prf("global %d Local %d\n", itsglobal, itslocal); } prf("global %d Local %d\n", itsglobal, itslocal); } Output Global 0 Local 1 Global 4 Local 2 Global 4 Local 1 8 2

Operators! Programmers manipulate variables using the operators provided by the high-level language.! Variables and operators combine to form expressions and statements.! These constructs denote the work to be done by the program.! Each operator may correspond to many machine instructions. Example: The multiply operator (*) typically requires multiple LC-3 ADD instructions. 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 9 10 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 */! Compound statement groups simple statements using braces. syntactically equivalent to a simple statement { z = x * y; y = y + 1; } 11 Operators Three things to know about each operator:! (1) Function what does the operator do?! (2) Precedence in which order are operators combined? Example: a * b + c * d" is the same as "(a * b) + (c * d) since multiply has 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 and subtract CS270 - Spring Semester associate 2014 left-to-right 12 3

Assignment Operator 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.! 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 right-hand side type conversion might make assigned value different than computed value! Assignment associates right to left. y = x = 3; y gets the value 3, because (x = 3) evaluates to the value 3. 13 14 Arithmetic Operators Arithmetic Expressions * multiply x * y 6 l-to-r / divide x / y 6 l-to-r % modulo x % y 6 l-to-r + add x + y 7 l-to-r - subtract x - y 7 l-to-r! All associate left to right.! * / % have higher precedence than + -.! Full precedence chart on page 602 of textbook! If mixed types, smaller type is "promoted" to larger. x + 4.3 if x is, converted to double and result is double! Integer division -- fraction is dropped. x / 3 if x is and x=5, result is 1 (not 1.666666...)! Modulo -- result is reder. x % 3 if x is and x=5, result is 2. 15 16 4

Bitwise Operators ~ 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.! Shift operations are logical (not arithmetic). Operate on values -- neither operand is changed. Logical Operators! logical NOT!x 4 r-to-l && logical AND x && y 14 l-to-r Logical OR x y 15 l-to-r! Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero).! Result of a logcial operation is always either TRUE (1) or FALSE (0). 17 18 Relational Operators Special Operators: ++ and -- > greater than x > y 9 l-to-r >= greater or equal x >= y 9 l-to-r < less than x < y 9 l-to-r < less or equal x <= y 9 l-to-r == equals x == y 10 l-to-r!= not equals x!= y 10 l-to-r! Result is 1 (TRUE) or 0 (FALSE).! Note: Don't confuse equality (==) with assignment (=)! ++ postincrement x++ 2 r-to-l -- postdecrement x-- 2 r-to-l ++ preincrement --x 3 r-to-l -- predecrement ++x 3 r-to-l! 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. 19 20 5

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) 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.! Note: Assignment operator has lowest precedence, so operations on the right-hand side are evaluated before assignment. 21 22 Special Operator: Conditional Symbol Operation! 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 Usage Precedence Assoc? : conditional x?y:z 16 l-to-r x Special Operators: +=, *=, etc.! 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. 23 24 6

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 0-3 -4-1 -5-2 Allocating Space for Variables! Global data section All global variables stored here R4 pos to beginning! Run-time stack Used for local variables R6 pos to top of stack R5 pos 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 25 26 Local Variable Storage Variables and Memory Locations! Local variables are stored in 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 poer 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. R5 Because stack grows downward, base is the highest address of the frame, and variable offsets are <= 0. seconds minutes hours time rate amount! 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? 27 28 7

Example: Compiling to LC-3 #include <stdio.h> inglobal; () { inlocal; /* local to */ outlocala; outlocalb; /* initialize */ inlocal = 5; inglobal = 3; /* perform calculations */ outlocala = inlocal++ & ~inglobal; outlocalb = (inlocal + inglobal) - (inlocal - inglobal); /* pr results */ prf("the results are: outlocala = %d, outlocalb = %d\n", outlocala, outlocalb); } Example: Symbol Table Name Type Offset Scope inglobal 0 global inlocal 0 outlocala -1 outlocalb -2 29 30 Example: Code Generation! ;! ; 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) Example (continued)! ; 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) 31 32 8

Example (continued)! ; 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, R5, #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) 33 9