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 BYU CS/ECEn 124 Variables and Operators 2 C What makes up a C program? Functions Global variables What are the two types of variables? Local (automatic) Global (static) BYU CS/ECEn 124 Variables and Operators 3 Variables & Operators Variables & Operators Variables are symbolic names that hold values Variable declarations include Variables are stored in memory or in registers. The compiler keeps track of A symbolic name Type (int, char, double) Scope (code region where the variable is defined) Where a variable value is currently stored When it needs to be moved from memory to a register, or from a register to memory Operators manipulate values BYU CS/ECEn 124 Variables and Operators 4 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 BYU CS/ECEn 124 Variables and Operators 5 Variables & Operators Compiling a Program C Source Code C Preprocessor Compiler Source Code Analysis Symbol Table Code Generation Library Object Files Linker Executable BYU CS/ECEn 124 Variables and Operators 6 Variables & Operators MSP430 C Variable Data Types Type Size Representation Minimum Maximum char, signed char 8 bits ASCII -128 127 unsigned char bool 8 bits ASCII 0 255 short, signed short 16 bits 2s complement -32768 32767 unsigned short 16 bits Binary 0 65535 int, signed int 16 bits 2s complement -32768 32767 unsigned int 16 bits Binary 0 65535 long, signed long 32 bits 2s complement -2,147,483,648 2,147,483,647 unsigned long 32 bits Binary 0 4,294,967,295 enum 16 bits 2s complement -32768 32767 float 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38 double 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38 long double 32 bits IEEE 32-bit 1.175495e-38 3.4028235e+38 pointers, references 16 bits Binary 0 0xFFFF function pointers 16 bits Binary 0 0xFFFF BYU CS/ECEn 124 Variables and Operators 7 Variables & Operators Variable Declarations int int i,j,k; i1, i2, i3, c3po; // declaring more than one variable // numbers OK, except for first letter int bananas = 10; // using an initializer int int monkey_count = 0; monkeyCount = 0; // two ways of doing ... // ... multi-word names int ab, Ab, aB, AB; int _compilerVar; // case sensitive names // compiler uses _ as first char char newline = ‘\n’; char lineBuffer[32]; // a character with an initializer // an array of 32 chars (a string) double double double double bananasPerMonkey; hugeNumber = 1.0E33; tinyNumber = 1.0E-33; fractionThing = 3.33333; BYU CS/ECEn 124 // // // // floating point declarations positive exponent negative exponent no exponent Variables and Operators 8 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 declaration { to the end of the block // begin block int chimp; 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 BYU CS/ECEn 124 Variables and Operators 9 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 declaration { to the end of the block // begin block int chimp; 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 BYU CS/ECEn 124 Variables and Operators 10 Variables Literals/ Constants Literals Constants Unnamed constant values used in programs area = 3.14159 * radius * radius; Variable declarations with prefixed with the const qualifier const double pi = 3.14159; Symbolic Values Created using preprocessor directive #define #define PI 3.14159 BYU CS/ECEn 124 Variables and Operators 11 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 BYU CS/ECEn 124 Variables and Operators 12 Variables Variable Naming Common naming conventions Hungarian notation (prefix hints) UpperCamelCase/lowerCamelCase for most identifiers #define TRUE 1 Names beginning with underscore are reserved for compilers/libraries and should not be used last_variable_used all-upper-case for constants MyInputByte, buzzerCounter Underscores gVariable __reserved or _Reserved Use a “style” throughout your program BYU CS/ECEn 124 Variables and Operators 13 Operators Operators Assignment – Arithmetic – equality, inequality, less-than, etc. Logical – AND, OR, XOR, NOT, and shifts on Integers Relational – add, subtract, multiply, divide Bitwise – changes the values of variables C supports a rich set of operators that allow the programmer to manipulate variables AND, OR, NOT on Booleans Increment/Decrement BYU CS/ECEn 124 Variables and Operators 14 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) { } BYU CS/ECEn 124 Variables and Operators 15 Operators The Assignment Operator The operator symbol is the equal sign: variable = expression 1) The expression on the right-hand side is evaluated 2) 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. BYU CS/ECEn 124 Variables and Operators 16 Operators The Assignment Operator variable = expression int x = 9; sub.w #2,sp mov.w #9,0(sp) Stack x = x + 4; sp add.w #4,0(sp) BYU CS/ECEn 124 Variables and Operators X 0x05fa 0x05fc 0x05fe 0x05f0 ... 0x0600 17 Operators Arithmetic Operators x + y Add + Subtract – Multiply * Divide / x – y x * y x / y x % y 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 BYU CS/ECEn 124 Variables and Operators 18 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) BYU CS/ECEn 124 Variables and Operators 19 Operators Bitwise Shifts Shifts are bitwise operators SHIFT LEFT << SHIFT RIGHT >> 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 Multiply by 4: x = x << 2; Divide by 8: x = x >> 3; BYU CS/ECEn 124 Variables and Operators 20 Operators Relational Operators Relational operators return Boolean values: Comparisons 0 if relation is FALSE 1 if relation is TRUE x x x x x x == y != y < y <= y > y >= y equality inequality less-than less-than-or-equal greater-than greater-than-or-equal Used most often in if-statements if(expression) statement; BYU CS/ECEn 124 Variables and Operators 21 Operators Mistake #1 – Beware! if(x = 1) statement; /* assign x to 1, and ... */ /* always execute statement */ if(x == 1) statement; /* if x is 1 then ... */ /* execute statement */ Most of you will make this mistake this semester. Some of you will spend hours trying to find it. BYU CS/ECEn 124 Variables and Operators 22 Operators Logical Operators AND && OR || NOT ! (2’s complement) f && g f || g !f 10 && 20 1 10 && 0 0 if(!x) statement; if(x == 0) statement; same if(x) statement; if(x != 0) statement; same BYU CS/ECEn 124 Variables and Operators 23 Operators Logical Operators Don’t confuse with Bitwise operators Logical operators take “Boolean” inputs and produce “Boolean” outputs Boolean inputs (how values are interpreted): Boolean outputs: Value not equal to zero TRUE Value equal to zero FALSE TRUE 1 FALSE 0 Not the same: BYU CS/ECEn 124 if( 'a' <= x <= 'z' ) statement; // wrong! if(('a' <= x) && (x <= 'z')) statement; Variables and Operators 24 Operators Increment/Decrement Operators x++ ++x x---x post-increment pre-increment post-decrement pre-decrement x x = 4; y = x++; x = 4; y = ++x; BYU CS/ECEn 124 5 5 x y 4 x = 4; y = x--; 3 4 5 x = 4; y = --x; 3 3 y Variables and Operators 25 Expressions Variable Coercion When executing expressions of mixed types, C automatically converts integer to floating point and back again as needed. 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) BYU CS/ECEn 124 Variables and Operators 26 Expressions Order of Evaluation Precedence Associativity The order in which operators and expressions are evaluated 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 BYU CS/ECEn 124 Variables and Operators 27 Expressions Order of Evaluation Precedence (*, /, %) > (+, –) a - b / c * d + e * f (( 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. BYU CS/ECEn 124 Variables and Operators 28 Expressions Operator Precedence/Associativity OPERATORS ( ) [ ] -> . ! ~ ++ -+ * & (type) sizeof * / % + << >> Bitwise < <= > >= Relational == != Relational & Bitwise ^ Bitwise | Bitwise && Logical || Logical ?: = += -= *= /= %= &= ^= |= <<= >>= , BYU CS/ECEn 124 Variables and Operators ASSOCIATIVITY left to right right to left left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right right to left left to right 29 Expressions Combined Assignment Operators Arithmetic and bitwise operators combined with the assignment operator. x x x x x x x x x x BYU CS/ECEn 124 += y; -= y; *= y; /= y; %= y; &= y; |= y; ^= y; <<= y; >>= y; x x x x x x x x x x = = = = = = = = = = x x x x x x x x x x + (y); – (y); * (y); / (y); % (y); & (y); | (y); ^ (y); << (y); >> (y); Variables and Operators 30 Expressions Conditional Expressions The conditional expression does a multiplexor operation in C: x ? y : z This expression returns the value of y if x!=0 otherwise it returns the value of z y z 1 0 x x ? y : z BYU CS/ECEn 124 Variables and Operators 31 C Compilation Allocating Space for C Variables Static storage class Global Variables Static Variables Allocated in Global Data Section Automatic storage class Local Variables Allocated in an Activation Record located on the Stack (Pointed to by stack pointer) 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. BYU CS/ECEn 124 Variables and Operators 32 C Compilation MSP430 Memory Layout 0000 I/O Space Global Data Section (Global and Static vars) Heap (Dynamically allocated vars) Run-Time Stack 0600 (Local and Auto vars) SP (R1) 8000 PC (R0) Program Code FFFF BYU CS/ECEn 124 Interrupt Vector Table Variables and Operators 33 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. BYU CS/ECEn 124 Variables and Operators 34 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. BYU CS/ECEn 124 Variables and Operators 35 C / Assembler C / Assembler Protocol Example f(w,x,y,z) Argument 4th (z) 3rd (y) 2nd (x) 1st (w) Return Value FIXXXX < 32-bit Type On the stack On the stack R13 R12 R12 32-bit Type On the stack On the stack R15:R14 R13:R12 R13:R12 struct/union On the stack On the stack On the stack On the stack Special Area 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. BYU CS/ECEn 124 Variables and Operators 36 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. BYU CS/ECEn 124 Variables and Operators 37 Coding Practices Hello, World! #include <stdio.h> #include <stdio.h> #define S(s)char x[]=#s;s int main() #define Q(x)x { #define A(x,y)y##x printf(“\nHello, World!”); #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)}}}) BYU CS/ECEn 124 Variables and Operators 38 Compilation Examples C to Assembly – Example 1 { int int int x = y = x y z x x = = = + + 0x8696: 0x869a: 0x86a0: 0x86a6: 0x86ac: 0x86b0: 0x86b4: 0x86b6: 0x86ba: 10; 20; 30; 4; y - z; } SP x y z ret adr Stack BYU CS/ECEn 124 8031 40B1 40B1 40B1 52A1 411F 512F 811F 4F81 0006 000A 0000 0014 0002 001E 0004 0000 0002 0004 0002 SUB.W MOV.W MOV.W MOV.W ADD.W MOV.W ADD.W SUB.W MOV.W #0x0006,SP #0x000a,0x0000(SP) #0x0014,0x0002(SP) #0x001e,0x0004(SP) #4,0x0000(SP) 0x0002(SP),R15 @SP,R15 0x0004(SP),R15 R15,0x0002(SP) x05f4 x05f6 x05f8 x05fa x05fc x05fe x0600 Variables and Operators 39 Compilation Examples C to Assembly – Example 2 int main(int argc, char* argv[]) { unsigned int x = 7; unsigned int y = 5; unsigned int z; z = x * y; return 0; } SP x05f4 argc (r12) x05f6 argv (r13) x05f8 x x05fa y x05fc z x05fe ret adr x0600 Stack BYU CS/ECEn 124 0x8040: 0x8044: 0x8048: 0x804c: 0x8052: 0x8058: 0x805c: 0x8060: 0x8064: 0x8068: 0x806a: 0x806e: main: 8031 000A 4D81 0002 4C81 0000 40B1 0007 0004 40B1 0005 0006 411C 0004 411D 0006 12B0 80DA 4C81 0008 430C 5031 000A 4130 __mpyi: 0x80da: 430E mpyi_add_loop: 0x80dc: C312 0x80de: 100C 0x80e0: 2801 0x80e2: 5D0E shift_test_mpyi: 0x80e4: 5D0D 0x80e6: 930C 0x80e8: 23F9 0x80ea: 4E0C 0x80ec: 4130 Variables and Operators SUB.W MOV.W MOV.W MOV.W MOV.W MOV.W MOV.W CALL MOV.W CLR.W ADD.W RET #0x000a,SP R13,0x0002(SP) R12,0x0000(SP) #0x0007,0x0004(SP) #0x0005,0x0006(SP) 0x0004(SP),R12 0x0006(SP),R13 #__mpyi R12,0x0008(SP) R12 #0x000a,SP CLR.W R14 CLRC RRC JLO ADD.W R12 (shift_test_mpyi) R13,R14 RLA.W TST.W JNE MOV.W RET R13 R12 (mpyi_add_loop) R14,R12 40 Compilation Examples C to Assembly– Example 3 int inGlobal; void main(void) { int outLocal; int inLocalA; int inLocalB; outLocal = inGobal+inLocalA+inLocalB; return; } Symbol Table BYU CS/ECEn 124 main: SUB.W MOV.W ADD.W ADD.W MOV.W ADD.W RET #0x0006,SP 0x0002(SP),R15 &inGlobal,R15 0x0004(SP),R15 R15,0x0000(SP) #0x0006,SP Identifier Type Storage Class Offset Scope inGlobal int Static absolute global inLocalA int Auto 2(SP) main inLocalB int Auto 4(SP) main outLocal int Auto 0(SP) main Variables and Operators 41 BYU CS/ECEn 124 Variables and Operators 42