S07: The C Language Required:PM: Ch 6, pgs 63-80 PM: Ch 8.4, pgs 114-118 Recommended: K&R, Chapters 1-4C program C++ Compiler 6.5Variables Global VariablesExpressions.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Chapter 11 Introduction to Programming in C
Programming Languages and Paradigms
Lecture 2 Introduction to C Programming
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.
Introduction to C Programming
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Primitive Variable types Basic types –char (single character or ASCII integer value) –int (integer) –short (not longer than int) –long (longer than int)
Structure of a C program
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
More on Numerical Computation CS-2301 B-term More on Numerical Computation CS-2301, System Programming for Non-majors (Slides include materials from.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
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
Introduction to C Programming
C Programming for Embedded Systems. fig_06_00 Computer Layers Low-level hardware to high-level software (4GL: “domain-specific”, report-driven, e.g.)
Chapter 11 - The C Language. BYU CS/ECEn 124Chapter 9 - Interrupts2 Dennis Ritchie ( ) Dennis Ritchie, the software developer who brought the.
Computer Science 210 Computer Organization Introduction to C.
Development. Development Environment Editor Assembler or compiler Embedded emulator/debugger IAR Embedded Workbench Kickstart Code Composer Essentials.
A First Book of ANSI C Fourth Edition
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
The C Language int i;main(){for(;i["]
Summer 2014 Chapter 1: Basic Concepts. Irvine, Kip R. Assembly Language for Intel-Based Computers 6/e, Chapter Overview Welcome to Assembly Language.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 11 Programming in C Compilation vs. Interpretation Different ways of translating high-level language Compilation translates code into machine.
The C Language.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 14 Functions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Chapter 12 – Types, Operators, Expressions First chimp in space.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Introduction to Programming
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.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
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.
CPS120: Introduction to Computer Science Variables and Constants.
C++ for Engineers and Scientists Second Edition
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.
CMPE13Cyrus Bazeghi 1 Chapter 11 Introduction to Programming in C.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
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.
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.
The Machine Model Memory
Computer Science 210 Computer Organization
Chapter 12 Variables and Operators
C Language VIVA Questions with Answers
C Short Overview Lembit Jürimägi.
C Basics.
Introduction to C Programming Language
Chapter 12 Variables and Operators
Chapter 11 Introduction to Programming in C
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Chapter 2: Introduction to C++.
The C Language: Intro.
Variables in C Topics Naming Variables Declaring Variables
C Language B. DHIVYA 17PCA140 II MCA.
Chapter 12 Variables and Operators
Presentation transcript:

S07: The C Language Required:PM: Ch 6, pgs PM: Ch 8.4, pgs Recommended: K&R, Chapters 1-4C program C++ Compiler 6.5Variables Global VariablesExpressions OperatorsControl Statements FunctionsLibrary FunctionsC program C++ Compiler 6.5Variables Global VariablesExpressions OperatorsControl Statements FunctionsLibrary Functions int i;main(){for(;i["]<i;++i){--i;}"];read('-'-'-',i+++"hell\ o, world!\\n",'/'/'/'));}read(j,i,p){write(j/p+p,i---j,i/i);} -- Dishonorable mention, Obfuscated C Code Contest, (Author requested anonymity.)

CS 224 BYU CS 224The C Language2 ChapterProjectHomework S00: Introduction Unit 1: Digital Logic S01: Data Types S02: Digital Logic L01: Warm-up L02: FSM HW01 HW02 Unit 2: ISA S03: ISA S04: Microarchitecture S05: Stacks / Interrupts S06: Assembly L03: Blinky L04: Microarch L05b: Traffic Light L06a: Morse Code HW03 HW04 HW05 HW06 Unit 3: C S07: C Language S08: Pointers S09: Structs S10: I/O L07b: Morse II L08a: Life L09a: Pong HW07 HW08 HW09 HW10

Learning Objectives… Learning Outcomes After completing this section, you should be able to Discuss the advantages of using a high level language. Explain the difference between a compiler and an interpreter. Summarize the function of the C preprocessor. Describe the compile/assembly/linker process. List the main features of a C Language program. Describe how C stream I/O works. BYU CS 224The C Language3 Topics Compilers vs. Interpreters C Program Symbol Table Variables & Operators Scope Expressions Precedence C Compilation Frames C / Assembler Coding Practices I/O Streams

Terms… Activation Record – A block of memory on the stack that is created when a function is called and contains all the local variables for a given invocation of a function. Arithmetic Operator – Operator that returns a numerical value. Associativity – The execution order of same precedence operators. Bitwise Operator – Operator that performs bitwise logical operations. Data type – Representation and valid operations of data object. Expression – Combination of variables / operators that returns a single value. Global (static) – Variable permanently assigned to a memory location. Literal – An immutable data object. Local (automatic) – Variable stored in a functions activation record. Logical Operator – Operator that returns a logical (true/false) value. Operator – Performs an operation on operand(s). Scope - Extent of a variable/function’s availability in a program. Precedence – The execution order of operators. Variable - Symbolic name for a memory location that hold a value. Variable Coercion – Forcing mixed data type variables to a common type. Volatile – Variable modifier that prohibits optiminization by compiler. BYU CS 224The C Language4

BYU CS 224The C Language5 Levels of Abstraction Problems Algorithms Language Machine (ISA) Architecture Microarchitecture Circuits Devices Transistors Logic gates, multiplexers, memory, etc. MSP430 Architecture Machine code Assembly code High Level Languages

BYU CS 224The C Language6 High Level Languages The closer a language is to your original specification, the easier the program is to write. Many, many programming languages LISP - LISt Processing PROLOG - logic programming MATLAB - matrix and vector manipulations BASIC – interpreter for small computers APL – matrix and vectors FORTRAN – formula translation COBOL – business and accounting PASCAL – procedural Ada – DOD large systems Java – Internet C, C++ …. High Level Languages

BYU CS 224The C Language7 High Level Languages Allow us to use symbolic names for values Programmer simply assigns each value a name Allow us to ignore many memory details. High Level Languages numberOfDays = 30; switch_A = ON; numberOfDays = 30; switch_A = ON; printf("Hello World!"); Provide abstraction of underlying hardware Hide low level details (ISA) from programmer Portable software (works on different ISAs) Provide expressiveness Express complex tasks with smaller amount of code English-like and human constructs if(isCloudy) get(umbrella); else get(sunglasses); if(isCloudy) get(umbrella); else get(sunglasses); main() { readInput(); checkForErrors(); doCalculation(); writeOutput(); } main() { readInput(); checkForErrors(); doCalculation(); writeOutput(); } Enhance code readability Can read like a novel… Easier to debug/maintain

BYU CS 224The C Language8 High Level Languages Provide safeguards against bugs Rules can lead to well-formed programs structured programming (no GOTO statements) Compilers can generate checks array bounds checking data type checking Many languages provide explicit support for assertions something that should be true - if it isn’t, then error High Level Languages assert(accountBalance >= 0); High-level languages make complex programming simpler, while low-level languages tend to produce more efficient code However, well-designed compilers frequently produce code comparable in efficiency to what most low-level programmers can produce by hand with better overall results

BYU CS 224The C Language9 Compilers vs Interpreters temp=v[i]; v[i]=v[i+1]; v[i+1]=temp; High-level language statements Compiler MOV.B 0x0001(SP),R14 MOV.W SP,R15 INCD.W R15 ADD.W R15,R14 MOV.B 0x0001(SP),R14 INC.W R14 Assembly Assembler 415E F 532F 5F0E 4EE E E Object code Application = Executable = Data Path temp=v[i]; v[i]=v[i+1]; v[i+1]=temp; Source code Interpreter Compilers vs Interpreters

BYU CS 224The C Language10 The C Programming Language Developed between 1969 and 1973 by Dennis Ritchie at Bell Labs. C first developed for use in writing compilers and operating systems (UNIX). A low-level high-level language Many variants of C 1989, the American National Standards Institute standardized C (ANSI C, most commonly used C) “The C Programming Language” by Kernighan and Ritchie is the C “Bible” (Also called the “White Book”.) C is one of the most popular programming languages of all time – very few computer architectures exist for which there is no C. C is predecessor to most of today’s procedural languages such as C++ and Java. The C Language

BYU CS 224The C Language11 Dennis Ritchie ( ) Dennis Ritchie, the software developer who brought the world the C programming language and Unix operating system, has died at the age of 70. Ritchie (known by the username "dmr") was part of a dynamic software development duo with Ken Thompson at Bell Labs,, which they joined in 1967 and 1966, respectively. Ritchie created the C programming language, which replaced the B programming language Thompson invented. Two years later in 1969, they created Unix, initially designed for minicomputers. Unix was initially written in 1969 in assembly language and later in C. Unix went on to become key software for critical computing infrastructure around the world. “UNIX is very simple, it just needs a genius to understand its simplicity.” --Dennis Ritchie

BYU CS 224The C Language12 Compiling a C Program The C Language Object Code Assembler Code C/C++ Code Machine Code

BYU CS 224The C Language13 Compiling a C Program The C Language Preprocessor Text C Source Code C Preprocessor Library & Object Files Executable Image Linker C Compiler Source Code Analysis 1 st Pass Symbol Table Assembler Code Generation 2 nd Pass Preprocessed C source code Assembly Code Object Code Machine Code

BYU CS 224The C Language14 A First Program //************************************ // blinky.c: Software Toggle P1.0 //************************************ #include "msp430.h" volatile unsigned int i; // no optimization void main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog P4DIR |= 0x40; // P4.6 output for (;;) // loop { P4OUT ^= 0x40; // toggle P4.6 while (--i); // delay } 1 st C Program Tells compiler to use all the definitions found in the msp430.h library. A.h file is called a header file and contains definitions and declarations. All C programs must have a main() routine. Stop WD w/Password Set P4.6 as output Loop forever Toggle P4.6 Delay 65,536 Allocate a RAM variable (.bss i,2)

BYU CS 224The C Language15 Style Use lots of comments /* This is a comment */ // This is a single line comment C Style Indents Each new scope is indented 2 spaces from previous Put { on end of previous line, or start of next line Line matching } up below Style is something of a personal matter. Everyone has their own opinions… What is presented here is similar to that in common use and a good place to start... if(a < b) { b = a; a = 0; } else { a = b; b = 0; } if(a < b) { b = a; a = 0; } else { a = b; b = 0; } Style 1 if(a < b) { b = a; a = 0; } else { a = b; b = 0; } if(a < b) { b = a; a = 0; } else { a = b; b = 0; } Style 2

BYU CS 224The C Language16 The C Preprocessor #define symbol code The preprocessor replaces symbol with code everywhere it appears in the program below #define NUMBER_OF_MONKEYS 259 #define MAX_LENGTH 80 #define PI #include filename.h The preprocessor replaces the #include directive itself with the contents of header file filename.h #include /* a system header file */ #include "myheader.h" /* a user header file */ Macros C Preprocessor #define add(x,y) x+=y #define doLoop(x,y) do {x} while(y); doLoop(add(z,2),z<10) do {z+=2} while(z<10);

A C Program What is a C program? Functions Global variables Variables are symbolic names for memory locations that hold values 2 types of variables Local (automatic) Global (static) Variable declarations include A symbolic name Data type (int, char, double) Scope (code region where the variable is defined) Variables are stored in memory or in registers. The compiler keeps track of where a variable’s value is currently stored. Operators manipulate values BYU CS 224The C Language17 C Program

The C Symbol Table The C compiler keeps track of variables in a program during compilation in a symbol table A symbol table entry is created when a variable is declared. Specifically, each symbol table entry contains: Variable name Variable data type (int, float, char, etc.) Variable storage class (auto, static) Where in memory the variable is stored (an offset) An identifier to indicate the variable’s scope Variables must be declared and in scope before they can be used (referenced) by a program BYU CS 224The C Language18 Variables & Operators

BYU CS 224The C Language19 Compiling a C Program The C Language Preprocessor Text C Source Code Library & Object Files Executable Image Linker C Compiler Source Code Analysis 1 st Pass Symbol Table Assembler Code Generation 2 nd Pass Preprocessed C source code Assembly Code Object Code Machine Code C Preprocessor

MSP430 C Variable Data Types TypeSizeRepresentationMinimumMaximum char, signed char8 bitsASCII unsigned charbool 8 bitsASCII0255 short, signed short16 bits2's complement unsigned short16 bitsBinary int, signed int16 bits2's complement unsigned int16 bitsBinary long, signed long32 bits2's complement-2,147,483,6482,147,483,647 unsigned long32 bitsBinary04,294,967,295 enum16 bits2's complement float32 bitsIEEE 32-bit e e+38 double32 bitsIEEE 32-bit e e+38 long double32 bitsIEEE 32-bit e e+38 pointers, references16 bitsBinary00xFFFF function pointers16 bitsBinary00xFFFF BYU CS 224The C Language20 Variables & Operators

Variable Declarations BYU CS 224The C Language21 int i,j,k; // declaring more than one variable int i1, i2, i3, c3po; // numbers OK, except for first letter int bananas = 10; // using an initializer int monkey_count = 0; // two ways of doing... int monkeyCount = 0; //... multi-word names int ab, Ab, aB, AB; // case sensitive names int _compilerVar; // compiler uses _ as first char char newline = ‘\n’; // a character with an initializer char lineBuffer[32]; // an array of 32 chars (a string) double bananasPerMonkey; // floating point declarations double hugeNumber = 1.0E33; // positive exponent double tinyNumber = 1.0E-33; // negative exponent double fractionThing = ; // no exponent Variables & Operators

Scope: Local versus Global Extent of a variable/function’s availability in a program Local Variables (automatic) Declared at the beginning of a block Stored in activation record on the stack Scope is from point of declaration to the end of the block Un-initialized Global Variables (static) Declared outside of a function Stored in Global Data Section of memory Scope is from point of declaration to the end of the program May be initialized to zero BYU CS 224The C Language22 { // begin block int chimp;... } Scope int chimp; { // begin block... }

Literals/ Constants Literal Values Unnamed constant values used in programs area = * radius * radius; Constant Variables Variable declarations prefixed with the const qualifier Immutable named variables const double pi = ; Symbolic Values Created using preprocessor directive #define #define PI How are the above the same? How are the above different? BYU CS 224The C Language23 Variables

Quiz 7.1 Expand the following C pre-processor macros: BYU CS 224The C Language24 #define MASK(bit) (0x80 >> ((bit)%8)) #define SET_CELL(a2d,row,col) a2d[row][(col)/8] |= MASK(col) #define CLEAR_CELL(a2d,row,col) a2d[row][(col)/8] &= ~ MASK(col) #define TEST_CELL(a1d,col) (a1d[(col)/8] & MASK(col)) 1.SET_CELL(life,row,col+1); 2.CLEAR_CELL(life,row,col); 3.if (TEST_CELL(temp,col)) {... };

Variable Usage Make your variable names meaningful Common naming conventions Hungarian notation (prefix hints) gVariable, hMyRoutine UpperCamelCase / lowerCamelCase for most identifiers MyInputByte, buzzerCounter Underscores last_variable_used, number_of_days all-upper-case for constants #define TRUE 1 Names beginning with underscore are reserved for compilers/libraries __reserved, _Reserved Encapsulate your variables Avoid global variables - explicitly pass parameters to functions Keep the scope as small as you can BYU CS 224The C Language25 Variables

volatile volatile proceeding a variable name instructs the compiler to prohibit caching the variable’s contents when optimizing code. always re-read the variable’s value when accessing the variable. not use computer registers to store a variable’s content. BYU CS 224The C Language26 volatile int switches,dcnt void main(void) { if (switches & 0x01) {...} } #pragma vector=PORT1_VECTOR __interrupt void Port_1_ISR(void) { P1IFG &= ~0x0f; // P1.0-3 IFG cleared dcnt = DEBOUNCE_CNT; // enable debounce } #pragma vector = WDT_VECTOR __interrupt void WDT_ISR(void) { if (dcnt && (--dcnt == 0)) switches = (P1IN ^ 0x0f) & 0x0f; } Inform the compiler that integers switches and dcnt are not to be optimized. Pressing a switch sets dcnt Sample P1IN when dcnt equals 0 Variables

Operators and Expressions Expressions are formed by combining variables with operators and ALWAYS return a single value in C. i = 5 * x + 100; a = (a < b); Operators Assignment – changes the values of variables Arithmetic – add, subtract, multiply, divide Bitwise – AND, OR, XOR, NOT, and shifts on Integers Relational – equality, inequality, less-than, etc. Logical – AND, OR, NOT on Booleans Increment/Decrement BYU CS 224The C Language27 C supports a rich set of operators that allow the programmer to manipulate variables Operators

The Assignment Operator The operator symbol is the equal sign The expression on the right-hand side is evaluated and assigned to the left-hand variable BYU CS 224The C Language28 { int x = 9; x = x + 4; } add.w #4,0(sp) sp X Stack 0x05fa 0x05fc 0x05fe 0x05f0 0x sub.w #2,sp mov.w #9,0(sp) Operators sp

Arithmetic / Relational Operators Arithmetic Operators Add (+), subtract (–), multiply (*), divide (/) Integer; 5/3 = 1 (truncated to int) Floating point : 5.0 / 3.0 = Modulus (%) Integer; remainder after integer division; 5 % 3 = 2 Relational operators return Boolean values: 0 if relation is FALSE 1 if relation is TRUE Comparisons x == yequality x != yinequality x < yless-than x <= yless-than-or-equal x > ygreater-than x >= ygreater-than-or-equal BYU CS 224The C Language29 x + y x – y x * y x / y x % y Operators

Bitwise Operators Perform bitwise logical operations across individual bits of a value. AND & OR | XOR ^ NOT ~ (1’s complement) Shifts are bitwise operators SHIFT LEFT << SHIFT RIGHT >> BYU CS 224The C Language30 x : (binary) y : (binary) x & y : (binary) x | y : (binary) x ^ y : (binary) ~x : (binary) Operators x << y shift x y-places to the left (add zeros) x >> y shift x y-places to the right (sign extend)

Logical Operators Logical operators evaluate to Boolean AND&& OR| | NOT! Don’t confuse with Bitwise operators Operate on Boolean inputs and produce Boolean outputs Boolean inputs (how values are interpreted): Value not equal to zero  TRUE Value equal to zero  FALSE BYU CS 224The C Language31 10 && 20  1 10 && 0  0 Operators if( 'a' <= x <= 'z' ) statement; // wrong! if(('a' <= x) && (x <= 'z')) statement; if(!x) statement; if(x == 0) statement; if(x) statement; if(x != 0) statement; Same

Order of Evaluation Variable Coercion When executing expressions of mixed types, C automatically converts integer to floating point and back again as needed. Avoid the use of forced data conversion as operators may yield unanticipated results. Order of expression evaluation: Precedence – higher precedence operators evaluate first. Associativity – operators of same precedence evaluate left to right (with a few exceptions). Parentheses override all other evaluation rules. BYU CS 224The C Language32 Expressions int x = 1; x is declared an integer x = x + 4.3; integer + floating point ?? (result is x = 5)

Operator Precedence/Associativity BYU CS 224The C Language33 OPERATORSASSOCIATIVITY ( ) [ ] ->.left to right ! ~ * & (type) sizeofright to left * / %left to right + -left to right >left to right >=left to right == !=left to right & ^ | &&left to right ||left to right ?:right to left = += -= *= /= %= &= ^= |= >=right to left,left to right Logical Relational Bitwise Expressions Unary operators associate right to left.

Quiz 7.2 Evaluate the variable result for the following: BYU CS 224The C Language34 1.int a = 1, b = 2, c = 3, d = 4, e = 5; int result = a * b + c / d * e; 2.int a = 6, b = 5, c = 4, d = 3; int result = c + (d = b * a); 3.int w = 5, x = 4, y = 3, z = 2; int result = w % x / y * z;

Combined Assignment Operators Arithmetic and bitwise operators can be combined with the assignment operator. BYU CS 224The C Language35 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); Expressions Note: All of the expression on the right is considered parenthesized.

Conditional Expressions Conditional expression C multiplexor operation Format: ? : Example: BYU CS 224The C Language36 Expressions printf("%d dog%s", dogs, (dogs == 1) ? "" : "s"); This expression returns the value of y if x != 0, otherwise it returns the value of z x ? y : z x yz 0 1

Quiz 7.3 What is the output? BYU CS 224The C Language37 main() { int i = 5,j = 10; i = i &= j && 10; printf("%d %d",i,j); } main() { int i = 4,j = 7; j = j || i++ && printf("Hello"); printf("%d %d", i, j); } 1. 2.

0x000a (x) C to Assembly – Example 1 BYU CS 224The C Language38 { int x = 10; int y = 20; int z = 30; x = x + 4; y = x + y - z; } 0x8696: SUB.W #0x0006,SP 0x869a: 40B1 000A 0000 MOV.W #0x000a,0x0000(SP) 0x86a0: 40B MOV.W #0x0014,0x0002(SP) 0x86a6: 40B1 001E 0004 MOV.W #0x001e,0x0004(SP) 0x86ac: 52A ADD.W #4,0x0000(SP) 0x86b0: 411F 0002 MOV.W 0x0002(SP),R15 0x86b4: 512F 0x86b6: 811F 0004 SUB.W 0x0004(SP),R15 0x86ba: 4F MOV.W R15,0x0002(SP) 0x86be: ADD.W #0x0006,SP SP Stack x0600 x05fe x05fc x05fa x05f8 x05f6 0x0014 (y) 0x001e (z) Compilation Examples SP 0x000e (x)

C to Assembly – Example 2 BYU CS 224The C Language39 int main(int argc, char** argv) { unsigned int x = 7; unsigned int y = 5; unsigned int z; z = x * y; return 0; } main: 0x8040: A SUB.W #0x000a,SP 0x8044: 4D MOV.W R13,0x0002(SP) 0x8048: 4C MOV.W R12,0x0000(SP) 0x804c: 40B MOV.W #0x0007,0x0004(SP) 0x8052: 40B MOV.W #0x0005,0x0006(SP) 0x8058: 411C 0004 MOV.W 0x0004(SP),R12 0x805c: 411D 0006 MOV.W 0x0006(SP),R13 0x8060: 12B0 80DA CALL #__mpyi 0x8064: 4C MOV.W R12,0x0008(SP) 0x8068: 430C CLR.W R12 0x806a: A ADD.W #0x000a,SP 0x806e: 4130 RET __mpyi: 0x80da: 430E CLR.W R14 mpyi_add_loop: 0x80dc: C312 CLRC 0x80de: 100C RRC R12 0x80e0: 2801 JLO (shift_test_mpyi) 0x80e2: 5D0E ADD.W R13,R14 shift_test_mpyi: 0x80e4: 5D0D RLA.W R13 0x80e6: 930C TST.W R12 0x80e8: 23F9 JNE (mpyi_add_loop) 0x80ea: 4E0C MOV.W R14,R12 0x80ec: 4130 RET SP Stack x0600 x05fe x05fc x05fa x05f4 x05f8 x05f6 ret adr argc (r12) argv (r13) z 0x0005 (y) 0x0007 (x) Compilation Examples SP

C to Assembly– Example 3 BYU CS 224The C Language40 main: SUB.W #0x0006,SP MOV.W 0x0002(SP),R15 ADD.W &inGlobal,R15 ADD.W 0x0004(SP),R15 MOV.W R15,0x0000(SP) ADD.W #0x0006,SP RET IdentifierTypeStorage ClassOffsetScope inGlobalintStaticabsoluteglobal inLocalAintAuto2(SP)main inLocalBintAuto4(SP)main outLocalintAuto0(SP)main Symbol Table int inGlobal; void main(void) { int outLocal; int inLocalA; int inLocalB; outLocal = inGobal + inLocalA + inLocalB; return; } Compilation Examples

Quiz 7.4 Fill in the resulting values for x, y, and z after evaluating the construct. Assume for each row, x, y, and z are initialized to 10, 20, and 30 respectively. BYU CS 224The C Language41 x=10y=20z=30 1)if (x = y) y = 100; 2) if (x < 10) y = 1; else if (x < 20) y = 5; else if (x < 30) y = 10; 3) switch ('a') { case 'a': y++; z *= 5; case 'b': --y; z /= 10; } 4)for (x=1; x<y; x++, y--) z = x + y; 5) while (!z) { z %= y; } 6)do { x = --y; z = x++; } while (z);

Streaming I/O in C

BYU CS 224The C Language43 C I/O I/O facilities are not part of the C language itself Nonetheless, programs do interact with their environment! Most digital I/O handled directly by C program #include "msp430.h" SPR’s, Ports, A/D, transponder, switches, LED’s, etc The ANSI standard defines a set of I/O library functions for portability Programs that confine their system interactions to facilities provided by the standard library can be moved from one system to another without change. The properties of the C I/O library functions are specified in header files #include (C standard library) #include "RBX430_lcd.h" C Stream I/O

BYU CS 224The C Language44 C Data Streams C I/O is character based, using streams. I/O streams must be opened / closed. In standard C there are 3 streams automatically opened before main() is called: stdin is the input stream stdout is the output stream stderr stream for error messages printf function outputs formatted values to stdout stream The printf function requires a format string followed by optional parameters: printf( "format string...", parameters... ); The format string contains two object types: Ordinary characters that are copied to the output stream Conversion specifications which cause conversion and printing of the next argument in the argument list. C Stream I/O

BYU CS 224The C Language45 Printf Output in C printf( format_string, parameters ) printf("Hello World"); printf("\n%d plus %d is %d", x, y, x+y); printf("\nIn hex it is %x", x+y); printf("\nHello, I am %s. ", myname); printf("\nIn ascii, 65 is %c. ", 65); Output: Hello world 5 plus 6 is 11 In hex it is b Hello, I am Bambi. In ascii, 65 is A. String literal Decimal Integer Hex Integer String Character Newline C Stream I/O

BYU CS 224The C Language46 RBX430_lcd.h Prototypes uint8 lcd_init(void); void lcd_clear(void); void lcd_backlight(uint8 backlight); void lcd_volume(uint8 volume); uint16 lcd_mode(int16 mode); uint8 lcd_cursor(uint16 x, uint16 y); uint16 lcd_printf(const char* fmt,...); uint8 lcd_image(const uint8* image, int16 x, int16 y); uint8 lcd_bitImage(const uint8* image, int16 x, int16 y, uint8 flag); uint8 lcd_wordImage(const uint16* image, int16 x, int16 y, uint8 flag); uint8 lcd_blank(int16 x, int16 y, uint16 w, uint16 h); uint8 lcd_point(int16 x, int16 y, uint8 flag); void lcd_circle(int16 x, int16 y, uint16 r, uint8 pen); void lcd_rectangle(int16 x, int16 y, uint16 w, uint16 h, uint8 pen); LCD I/O

BYU CS 224The C Language47 LCD – 160 x 160 x 5 Pixels Y (0-159)  Hello World! lcd_init(); lcd_clear(); // 5 x 8 pixel Characters lcd_cursor(40, 60); lcd_printf("Hello World!"); X (0-159)  LCD I/O

BYU CS 224The C Language48