Download presentation
Presentation is loading. Please wait.
Published byLenard Jennings Modified over 8 years ago
1
Chapter 12 – Types, Operators, Expressions First chimp in space
2
BYU CS/ECEn 124Variables and Operators2 Topics to Cover… Variables & Operators Scope Variables Logical Operators Increment/Decrement Operators Operators Expressions C Compilation Frames C / Assembler Coding Practices Compilation Examples
3
BYU CS/ECEn 124Variables and Operators3 C What makes up a C program? Functions Global variables What are the two types of variables? Local (automatic) Global (static)
4
BYU CS/ECEn 124Variables and Operators4 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, or from a register to memory Operators manipulate values Variables & Operators
5
BYU CS/ECEn 124Variables and Operators5 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 & Operators
6
BYU CS/ECEn 124Variables and Operators6 Compiler Compiling a Program Source Code Analysis Code Generation Linker C Source Code C Preprocessor Library Object Files Executable Symbol Table Variables & Operators
7
BYU CS/ECEn 124Variables and Operators7 MSP430 C Variable Data Types TypeSizeRepresentationMinimumMaximum char, signed char8 bitsASCII-128127 unsigned charbool 8 bitsASCII0255 short, signed short16 bits2s complement-3276832767 unsigned short16 bitsBinary065535 int, signed int16 bits2s complement-3276832767 unsigned int16 bitsBinary065535 long, signed long32 bits2s complement-2,147,483,6482,147,483,647 unsigned long32 bitsBinary04,294,967,295 enum16 bits2s complement-3276832767 float32 bitsIEEE 32-bit1.175495e-383.4028235e+38 double32 bitsIEEE 32-bit1.175495e-383.4028235e+38 long double32 bitsIEEE 32-bit1.175495e-383.4028235e+38 pointers, references16 bitsBinary00xFFFF function pointers16 bitsBinary00xFFFF Variables & Operators
8
BYU CS/ECEn 124Variables and Operators8 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 & Operators
9
BYU CS/ECEn 124Variables and Operators9 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 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;... } Scope
10
BYU CS/ECEn 124Variables and Operators10 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 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;... } Scope
11
BYU CS/ECEn 124Variables and Operators11 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
12
BYU CS/ECEn 124Variables and Operators12 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
13
BYU CS/ECEn 124Variables and Operators13 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
14
BYU CS/ECEn 124Variables and Operators14 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 Operators
15
BYU CS/ECEn 124Variables and Operators15 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) { } Operators
16
BYU CS/ECEn 124Variables and Operators16 The Assignment Operator 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. variable = expression The operator symbol is the equal sign: Operators
17
BYU CS/ECEn 124Variables and Operators17 The Assignment Operator int x = 9; x = x + 4; add.w #4,0(sp) sp X Stack 0x05fa 0x05fc 0x05fe 0x05f0 variable = expression 0x0600... sub.w #2,sp mov.w #9,0(sp) Operators
18
BYU CS/ECEn 124Variables and Operators18 Arithmetic Operators 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 x + y x – y x * y x / y x % y Operators
19
BYU CS/ECEn 124Variables and Operators19 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) Operators
20
BYU CS/ECEn 124Variables and Operators20 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 Operators
21
BYU CS/ECEn 124Variables and Operators21 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; Operators
22
BYU CS/ECEn 124Variables and Operators22 Mistake #1 – Beware! 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. if(x = 1) /* assign x to 1, and... */ statement; /* always execute statement */ Operators
23
BYU CS/ECEn 124Variables and Operators23 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; Operators
24
BYU CS/ECEn 124Variables and Operators24 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; Operators
25
BYU CS/ECEn 124Variables and Operators25 Increment/Decrement Operators x++ post-increment ++x pre-increment x-- post-decrement --x pre-decrement x = 4; y = x++; x = 4; y = ++x; x = 4; y = x--; x = 4; y = --x; x y 5 4 5 x y 3 4 3 Operators
26
BYU CS/ECEn 124Variables and Operators26 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) Expressions
27
BYU CS/ECEn 124Variables and Operators27 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 Expressions
28
BYU CS/ECEn 124Variables and Operators28 Order of Evaluation Precedence (*, /, %) > (+, –) Even with precedence, use of parentheses can make code more readable. Stylistically, it is preferable to use parentheses even when they are not needed. (( a - (( b / c ) * d )) + ( e * f )) a - b / c * d + e * f Expressions
29
BYU CS/ECEn 124Variables and Operators29 Operator Precedence/Associativity 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 ?:left to right = += -= *= /= %= &= ^= |= >=right to left,left to right Logical Relational Bitwise Expressions
30
BYU CS/ECEn 124Variables and Operators30 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); Expressions
31
BYU CS/ECEn 124Variables and Operators31 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 x yz 10 x ? y : z Expressions
32
BYU CS/ECEn 124Variables and Operators32 Allocating Space for C Variables Automatic storage class Local Variables Allocated in Global Data Section 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. Static storage class Global Variables Static Variables C Compilation
33
BYU CS/ECEn 124Variables and Operators33 MSP430 Memory Layout Global Data Section (Global and Static vars) Run-Time Stack (Local and Auto vars) SP (R1) PC (R0) 0000 FFFF Heap (Dynamically allocated vars) I/O Space Interrupt Vector Table 8000 Program Code 0600 C Compilation
34
BYU CS/ECEn 124Variables and Operators34 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. Frames
35
BYU CS/ECEn 124Variables and Operators35 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. Frames
36
BYU CS/ECEn 124Variables and Operators36 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. C / Assembler Argument< 32-bit Type32-bit Typestruct/union 4 th (z)On the stack 3 rd (y)On the stack 2 nd (x)R13R15:R14On the stack 1 st (w)R12R13:R12On the stack Return ValueR12R13:R12Special Area
37
BYU CS/ECEn 124Variables and Operators37 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. Coding Practices
38
BYU CS/ECEn 124Variables and Operators38 Hello, World! #include #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 int main() { printf(“\nHello, World!”); } Coding Practices
39
BYU CS/ECEn 124Variables and Operators39 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) SP Stack x05f4 x05f6 x05f8 x05fa x0600 x05fc x05fe ret adr x y z Compilation Examples
40
BYU CS/ECEn 124Variables and Operators40 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; } 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 SP Stack x05f4 x05f6 x05f8 x05fa x0600 x05fc x05fe ret adr argc (r12) argv (r13) x y z Compilation Examples
41
BYU CS/ECEn 124Variables and Operators41 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 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
42
BYU CS/ECEn 124Variables and Operators42
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.