420 likes | 596 Views
Chapter 12 – Types, Operators, Expressions. First chimp in space. Topics to Cover…. Variables & Operators Scope Variables Logical Operators Increment/Decrement Operators Operators Expressions C Compilation Frames C / Assembler Coding Practices Compilation Examples. C.
E N D
Chapter 12 –Types, Operators, Expressions First chimp in space
Topics to Cover… • Variables & Operators • Scope • Variables • Logical Operators • Increment/Decrement Operators • Operators • Expressions • C Compilation • Frames • C / Assembler • Coding Practices • Compilation Examples Variables and Operators
C • What makes up a C program? • Functions • Global variables • What are the two types of variables? • Local (automatic) • Global (static) Variables and Operators
Variables & Operators Variables & Operators • Variables are symbolic names that hold values • Variable declarations include • A symbolic name • 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 value is currently stored • When it needs to be moved from memory to a register, orfrom a register to memory • Operators manipulate values Variables and Operators
Variables & Operators The C Symbol Table • The C compiler keeps track of variables in a program with a symbol table • A symbol table entry is created when a variable is declared. • Each entry contains: • Variable name • Variable type (int, float, char, etc.) • Variable storage class (auto, static) • Where in memory variable is stored (an offset) • An identifier to indicate the variable’s scope Variables and Operators
C Preprocessor Linker Library Object Files Executable Variables & Operators Compiling a Program C Source Code Compiler Source Code Analysis Symbol Table Code Generation Variables and Operators
Variables & Operators MSP430 C Variable Data Types Variables and Operators
Variables & Operators Variable Declarations 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 = 3.33333; // no exponent Variables and Operators
Scope Scope: Local versus Global • Local Variables (automatic) • Declared at the beginning of a block • Stored in activation record on the stack • Scope is from point of declarationto the end of the block • Un-initialized • Global Variables (static) • Declared outside of a function • Stored in Global Data Section of memory • Scope is entire program • May be initialized to zero { // begin block int chimp; ...} Variables and Operators
Scope Scope: Local versus Global • Local Variables • Declared at the beginning of a block • Stored in activation record on the stack • Scope is from point of declarationto the end of the block • Un-initialized • Global Variables • Declared outside of a function • Stored in Global Data Section of memory • Scope is entire program • May be initialized to zero { // begin block int chimp; ...} Variables and Operators
Variables Literals/ Constants • Literals • Unnamed constant values used in programs • area = 3.14159 * radius * radius; • Constants • Variable declarations with prefixed with the const qualifier • const double pi = 3.14159; • Symbolic Values • Created using preprocessor directive #define • #define PI 3.14159 Variables and Operators
Variables Variable Usage • Make your variable names meaningful • to reduce the effort needed to read and understand source code • to enhance source code appearance • Encapsulate your variables • Avoid global variables • Explicitly pass parameters to functions • Explicitly return function results • Keep declarations as close as you can to where you use the variables • Keep the scope as small as you can • Explicitly Variables and Operators
Variables Variable Naming • Common naming conventions • Hungarian notation (prefix hints) • gVariable • UpperCamelCase/lowerCamelCase for most identifiers • MyInputByte, buzzerCounter • Underscores • last_variable_used • all-upper-case for constants • #define TRUE 1 • Names beginning with underscore are reserved for compilers/libraries and should not be used • __reserved or _Reserved • Use a “style” throughout your program Variables and Operators
Operators 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 C supports a rich set of operators that allow the programmer to manipulate variables Variables and Operators
Operators Operators and Expressions • Expressions are formed by combining variable and literal values with operators • Expressions ALWAYS return a single value in C • A statement is defined by the syntax of C and often includes an expression, but not always • int i; • int i = 4; • i = 5; • i < j; • a = (a < b); • while(0) { } Variables and Operators
Operators The Assignment Operator • The expression on the right-hand side is evaluated • The value is assigned to the left-hand variable • Different meaning than in Mathematics • In math, “X = Y” asserts that X and Y are the same value. • In C, “X = Y” changes the value of X to be the same as Y. • The operator symbol is the equal sign: variable = expression Variables and Operators
Operators The Assignment Operator variable = expression int x = 9; x = x + 4; sub.w #2,sp mov.w #9,0(sp) Stack 0x05fa 0x05fc 0x05fe sp 0x05f0 X add.w #4,0(sp) ... 0x0600 Variables and Operators
Operators Arithmetic Operators x + y x – y x * y x / y x % y • Add + • Subtract – • Multiply * • Divide / • Integer; integer division; 5/3 = 1 (truncated to int) • Floating point : 5.0 / 3.0 = 1.66666666 • Modulus % • Integer; remainder after integer division; 5 % 3 = 2 Variables and Operators
Operators Bitwise Operators • Perform logical operations across individual bits of a value. • AND & • OR | • XOR ^ • NOT ~ (1’s complement) x : 1 0 1 0 (binary) y : 1 1 0 0 (binary) x & y : 1 0 0 0 (binary) x | y : 1 1 1 0 (binary) x ^ y : 0 1 1 0 (binary) ~x : 0 1 0 1 (binary) Variables and Operators
Operators Bitwise Shifts • Shifts are bitwise operators • SHIFT LEFT << • SHIFT RIGHT >> • Multiply by 4: x = x << 2; • Divide by 8: x = x >> 3; x << y : shift x y-places to the left add zeros on the right x >> y : shift x y-places to the right sign extend on the left Variables and Operators
Operators Relational Operators • Relational operators return Boolean values: • 0 if relation is FALSE • 1 if relation is TRUE • Comparisons • x == y equality • x != y inequality • x < y less-than • x <= y less-than-or-equal • x > y greater-than • x >= y greater-than-or-equal • Used most often in if-statements • if(expression) statement; Variables and Operators
Operators Mistake #1 – Beware! if(x = 1) /* assign x to 1, and ... */ statement; /* always execute statement */ if(x == 1) /* if x is 1 then ... */ statement; /* execute statement */ Most of you will make this mistake this semester. Some of you will spend hours trying to find it. Variables and Operators
same same Operators Logical Operators • AND && • OR | | • NOT ! (2’s complement) f && g f || g !f 10 && 20 110 && 0 0 if(!x) statement;if(x == 0) statement; if(x) statement;if(x != 0) statement; Variables and Operators
Operators Logical Operators • Don’t confuse with Bitwise operators • Logical operators take “Boolean” inputs and produce “Boolean” outputs • Boolean inputs (how values are interpreted): • Value not equal to zero TRUE • Value equal to zero FALSE • Boolean outputs: • TRUE 1 • FALSE 0 • Not the same: if( 'a' <= x <= 'z' ) statement; // wrong! if(('a' <= x) && (x <= 'z')) statement; Variables and Operators
x y3 4 3 3 x y5 4 5 5 x = 4;y = x++; x = 4;y = ++x; x = 4;y = x--; x = 4;y = --x; Operators Increment/Decrement Operators • x++ post-increment • ++x pre-increment • x-- post-decrement • --x pre-decrement Variables and Operators
int x = 1; x is declared an integer x = x + 4.3; integer + floating point ?? x is converted to floating point floating point addition result is converted (truncated) back to integer for assignment (result is x = 5) Expressions Variable Coercion • When executing expressions of mixed types, C automatically converts integer to floating point and back again as needed. Variables and Operators
Expressions Order of Evaluation • Precedence • The order in which operators and expressions are evaluated • Associativity • The order which in which operators of the same precedence are evaluated • Left to Right for +, – , *, /, % • Right to Left for some other operators • Parentheses • Override the evaluation rules Variables and Operators
(( a - (( b / c ) * d )) + ( e * f )) Expressions Order of Evaluation • Precedence (*, /, %) > (+, –) a - b / c * d + e * f Even with precedence, use of parentheses can make code more readable. Stylistically, it is preferable to use parentheses even when they are not needed. Variables and Operators
Bitwise Relational Relational Bitwise Bitwise Bitwise Logical Logical Expressions Operator Precedence/Associativity Variables and Operators
Expressions Combined Assignment Operators • Arithmetic and bitwise operators combined with the assignment operator. 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); Variables and Operators
y z 1 0 x x ? y : z Expressions Conditional Expressions • The conditional expression does a multiplexor operation in C: x ? y : z This expression returns the value of y if x!=0otherwise it returns the value of z Variables and Operators
Allocated in Global Data Section Allocated in an Activation Recordlocated on the Stack (Pointed to by stack pointer) C Compilation Allocating Space for C Variables • Static storage class • Global Variables • Static Variables • Automatic storage class • Local Variables An activation record is a block of memory on the stack that is created when a function is called. It contains all the local variables for a given invocation of a function. Variables and Operators
SP (R1) PC (R0) C Compilation MSP430 Memory Layout 0000 I/O Space Global Data Section(Global and Static vars) Heap(Dynamically allocated vars) Run-Time Stack(Local and Auto vars) 0600 8000 Program Code FFFF Interrupt Vector Table Variables and Operators
Frames Compiler Register Usage • The scratch registers R12 to R15 are used for parameter passing and hence are not normally preserved across the call. • The other general-purpose registers, R4 to R11, are mainly used for register variables and temporary results and must be preserved across a call. • This is handled automatically within C. Variables and Operators
Frames Stack Frames / Parameter Passing • The parameters of a called function are passed to an assembler routine in a right to left order. • Up to four left most parameters are passed in registers unless they are defined as a struct or union type, in which case they are also passed on the stack. The remaining parameters are always passed on the stack. Variables and Operators
C / Assembler C / Assembler Protocol Example • f(w,x,y,z) FIXXXX • Arguments are evaluated right to left: • z is pushed onto the stack first, • followed by y onto the stack, • followed by w and x in registers r12 and r13 respectively. • The result is returned in R12 (or R13:R12 for a 32 bit type) or in a special area pointed to by R12 if it is a struct or union type. Variables and Operators
Coding Practices Good Coding Practices… • Keep the lifetime of variables as short as possible. • Keep the scope of variables as small as possible. • Use variables and routines for one and only one purpose. • Avoid creating multipurpose routines that perform a variety of unrelated functions. • Avoid the use of forced data conversion, sometimes referred to as variable coercion or casting, which may yield unanticipated results. Variables and Operators
Coding Practices Hello, World! #include <stdio.h> #define S(s)char x[]=#s;s #define Q(x)x #define A(x,y)y##x #define B(x,y)A(y,x) #define C(x,y)B(y,x) #define Z(s,t,u)case s:if(*p!=32){t;}else{u;}break; S(B( A( a ,m ),A(n ,i))() {B (A(h,c ),A(r ,a ))*p=x ;B(A( n, i),t)t \ =0;B(A(n , i),t)s =0;B( f ,A(r, o )) (;*p;Q( p)++){C( B( A(c,t) ,h),B(A( \ w, s),i))( s){ Z( 0,t+=8 *8-00 ,s ++)Z( 1,t+= 8 ;,s++ )Z \ ( 2, t++ ,putchar(t-73);t=s=0)}}}) #include <stdio.h> int main() { printf(“\nHello, World!”); } Variables and Operators
Compilation Examples C to Assembly – Example 1 { int x = 10; int y = 20; int z = 30; x = x + 4; y = x + y - z; } 0x8696: 8031 0006 SUB.W #0x0006,SP 0x869a: 40B1 000A 0000 MOV.W #0x000a,0x0000(SP) 0x86a0: 40B1 0014 0002 MOV.W #0x0014,0x0002(SP) 0x86a6: 40B1 001E 0004 MOV.W #0x001e,0x0004(SP) 0x86ac: 52A1 0000 ADD.W #4,0x0000(SP) 0x86b0: 411F 0002 MOV.W 0x0002(SP),R15 0x86b4: 512F ADD.W @SP,R15 0x86b6: 811F 0004 SUB.W 0x0004(SP),R15 0x86ba: 4F81 0002 MOV.W R15,0x0002(SP) x05f4 x05f6 x05f8 SP x x05fa y x05fc z x05fe ret adr x0600 Stack Variables and Operators
Compilation Examples C to Assembly – Example 2 main: 0x8040: 8031 000A SUB.W #0x000a,SP 0x8044: 4D81 0002 MOV.W R13,0x0002(SP) 0x8048: 4C81 0000 MOV.W R12,0x0000(SP) 0x804c: 40B1 0007 0004 MOV.W #0x0007,0x0004(SP) 0x8052: 40B1 0005 0006 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: 4C81 0008 MOV.W R12,0x0008(SP) 0x8068: 430C CLR.W R12 0x806a: 5031 000A 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 int main(int argc, char* argv[]) { unsigned int x = 7; unsigned int y = 5; unsigned int z; z = x * y; return 0; } x05f4 SP argc (r12) x05f6 argv (r13) x05f8 x x05fa y x05fc z x05fe ret adr x0600 Stack Variables and Operators
IdentifierTypeStorage ClassOffsetScope inGlobal int Static absolute global inLocalA int Auto 2(SP) main inLocalB int Auto 4(SP) main outLocal int Auto 0(SP) main SymbolTable Compilation Examples C to Assembly– Example 3 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 int inGlobal; void main(void) { int outLocal; int inLocalA; int inLocalB; outLocal = inGobal+inLocalA+inLocalB; return; } Variables and Operators