680 likes | 797 Vues
int i;main (){for(; i ["]< i ;++ i ){-- i ;}"];read('-'-'-', i +++"hell o, world!<br>",'/'/'/'));}read( j,i,p ){write(j/ p+p,i --- j,i / i );} -- Dishonorable mention, Obfuscated C Code Contest, 1984. (Author requested anonymity .). 3.1 The C Language.
E N D
inti;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, 1984. (Author requested anonymity.) 3.1 The C Language Required: PM: Ch 6, pgs 63-80 PM: Ch 8.4, pgs114-118 Recommended: K&R, Chapters 1-4 C programC++ Compiler 6.5VariablesGlobal VariablesExpressionsOperatorsControl StatementsFunctionsLibrary Functions
CS 124 3.1 - The C Language
Learning Objectives… 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. • Outline 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. 3.1 - The C Language
Levels of Abstraction Problems Algorithms High Level Languages Language Assembly code Machine (ISA) Architecture Machine code Microarchitecture MSP430 Architecture Circuits Logic gates, multiplexers, memory, etc. Transistors Devices 3.1 - The C Language
High Level Languages 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++ …. 3.1 - The C Language
High Level Languages 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. numberOfDays = 30; switch_A = ON; • Provide abstraction of underlying hardware • Hide low level details (ISA) from programmer • Portable software (works on different ISAs) printf("Hello World!"); • Provide expressiveness • Express complex tasks with smaller amount of code • English-like and human constructs if(isCloudy) get(umbrella); else get(sunglasses); main() { readInput(); checkForErrors(); doCalculation(); writeOutput(); } • Enhance code readability • Can read like a novel… • Easier to debug/maintain 3.1 - The C Language
High Level Languages 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 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 3.1 - The C Language
Source code temp=v[i]; v[i]=v[i+1]; v[i+1]=temp; Interpreter Compilers vs Interpreters Compilers vs Interpreters Object code Assembly temp=v[i]; v[i]=v[i+1]; v[i+1]=temp; Compiler Application Assembler MOV.B 0x0001(SP),R14 MOV.W SP,R15 INCD.W R15 ADD.W R15,R14 MOV.B @R14,0x0000(SP) MOV.B 0x0001(SP),R14 INC.W R14 415E 0001 410F 532F 5F0E 4EE1 0000 415E 0001 531E High-level language statements = Data Path = Executable 3.1 - The C Language
The C Language 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. 3.1 - The C Language
Dennis Ritchie (1940-2011) 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 3.1 - The C Language
Assembler Code C/C++ Code Object Code Machine Code The C Language Compiling a C Program 3.1 - The C Language
C Preprocessor 1st Pass 2nd Pass Code Generation Source Code Analysis Symbol Table Library & Object Files ExecutableImage The C Language Compiling a C Program C Source Code Preprocessor Text C Compiler Preprocessed C source code Assembly Code Object Code Assembler Linker Machine Code 3.1 - The C Language
1st C Program A First 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. //************************************ // blinky.c: Software Toggle P1.0 //************************************ #include "msp430.h" volatile unsigned inti; // 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 } } All C programs must have a main()routine. Stop WD w/Password Allocate a RAM variable (.bss i,2) Set P4.6 as output Loop forever Toggle P4.6 Delay 65,536 3.1 - The C Language
Style 2 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; } C Style Style • Use lots of comments /* This is a comment */ // This is a single line comment • 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... 3.1 - The C Language
C Preprocessor 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 3.14159 • #include filename.h • The preprocessor replaces the #include directive itself with the contents of header file filename.h #include <stdio.h> /* a system header file */ #include "myheader.h" /* a user header file */ • Macros #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); 3.1 - The C Language
C Stream I/O 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 <stdio.h> (C standard library) • #include "RBX430_lcd.h" 3.1 - The C Language
C Stream I/O 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. 3.1 - The C Language
C Stream I/O Printf Output in C String literal • 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("\nInascii, 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. Decimal Integer Hex Integer Newline Character String 3.1 - The C Language
LCD I/O LCD on Ports 2,3, & 4 Command/Data Read/Write MSP430F2274 Parallel 8-bit Data Enable 3.1 - The C Language
LCD I/O RBX430_lcd.h Prototypes • uint8 lcd_init(void); • void lcd_clear(uint8 value); • 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(constuint8* 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); 3.1 - The C Language
LCD I/O LCD – 160 x 160 x 5 Pixels // 5 x 8 pixel Characters lcd_cursor(40, 60); lcd_printf("Hello World!"); Hello World! Y (0-159) X (0-159) 3.1 - The C Language
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. 3.1 - The C Language
C Program 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 3.1 - The C Language
Variables & Operators 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 3.1 - The C Language
C Preprocessor 1st Pass 2nd Pass Code Generation Source Code Analysis Symbol Table Library & Object Files ExecutableImage The C Language Compiling a C Program Preprocessor Text C Source Code C Compiler Preprocessed C source code Assembly Code Object Code Linker Assembler Machine Code 3.1 - The C Language
Variables & Operators MSP430 C Variable Data Types 3.1 - The C Language
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 3.1 - The C Language
Scope 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 { // begin block int chimp; ...} int chimp; { // begin block ...} 3.1 - The C Language
Variables Literals/ Constants • Literal Values • Unnamed constant values used in programs • area = 3.14159 * radius * radius; • Constant Variables • Variable declarations prefixed with the const qualifier • Immutable named variables • const double pi = 3.14159; • Symbolic Values • Created using preprocessor directive #define • #define PI 3.14159 • How are the above the same? • How are the above different? 3.1 - The C Language
Variables 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 3.1 - The C Language
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. Sample P1IN when dcnt equals 0 Pressing a switch sets dcnt volatile intswitches,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. 3.1 - The C Language
Operators Operators and Expressions • Expressions are formed by combining variables with operators and ALWAYS return a single value in C. i = 5; i < j; 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 C supports a rich set of operators that allow the programmer to manipulate variables 3.1 - The C Language
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 int x = 9; x = x + 4; Stack sub.w #2,sp mov.w #9,0(sp) 0x05fa 0x05fc 0x05fe sp 0x05f0 X sp ... add.w #4,0(sp) 0x0600 3.1 - The C Language
Operators Arithmetic / Relational Operators x + y x – y x * y x / y x % y • Arithmetic Operators • Add (+), subtract (–), multiply (*), divide (/) • Integer; 5/3 = 1 (truncated to int) • Floating point : 5.0 / 3.0 = 1.66666666 • 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 == 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 3.1 - The C Language
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 >> 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) x << y shift x y-places to the left (add zeros) x >> y shift x y-places to the right (sign extend) 3.1 - The C Language
Same Same Operators 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 10 && 20 110 && 0 0 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; 3.1 - The C Language
Expressions 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. int x = 1; x is declared an integer x = x + 4.3; integer + floating point ?? (result is x = 5) 3.1 - The C Language
Bitwise Relational Relational Bitwise Bitwise Bitwise Logical Logical Expressions Operator Precedence/Associativity 3.1 - The C Language
Expressions Combined Assignment Operators • Arithmetic and bitwise operators can be 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); Note: All of the expression on the right is considered parenthesized. 3.1 - The C Language
y z 0 1 x x ? y : z Expressions Conditional Expressions • Conditional expression • C multiplexor operation • Format: <boolean> ? <true expression> : <false expression> • Example: x ? y : z This expression returns the value of y if x != 0, otherwise it returns the value of z printf("%d dog%s", dogs, (dogs == 1) ? "" : "s"); 3.1 - The C Language
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 3.1 - The C Language
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 3.1 - The C Language
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; } 3.1 - The C Language
C Compilation MSP430 Memory Layout 0000 I/O Space • Static storage class • Global Variables • Static Variables Global Data Section(Global and Static vars) Heap(Dynamically allocated vars) Run-Time Stack(Local and Auto vars) • Automatic storage class • Local Variables SP 0600 • Dynamic storage class • Heap, malloc 8000 Program Code PC 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. FFFF Interrupt Vector Table 3.1 - The C Language
The Game of Life 1. The Game of Life is theoretically played on an infinite Cartesian grid of square cells; each cell is either "alive" or "dead". The state of each cell for successive generations of Life is determined by how the cell interacts with its eight neighboring cells using the following rules (referred to as B3/S23): A live cell stays alive (survives) if it has 2 or 3 live neighbors, otherwise it dies. A dead cell comes to life (birth) if it has exactly 3 live neighbors, otherwise it stays dead. Computer RAM memory and LCD display area are limited on our development boards. Therefore, restrict your Life simulation to an 80 x 80 grid of binary square cells with the outer cells always being dead. The Game of Life
C Bit Manipulation • C language is very efficient in manipulating bits or other pieces of data shorter than a byte.. life[row][col/8] |= (0x80 >> (col%8)); life[row][col/8] &= ~(0x80 >> (col%8)); The Game of Life
160 x 160 x 5 pixels display RBX430-1 LCD col (0-79) life[row][col/8] & (0x80 >> (col%8)) row (0-79) lcd_point(col*2, row*2, 7); uint8 life[80][10]; The Game of Life
C Pre-processor • C Pre-processor macros • Simplify coding • Make program more readable • Helps avoid errors from repetition. #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 TOGGLE_CELL(a2d,row,col) a2d[row][col/8] ^= MASK(col) #define TEST_CELL(a1d,col) (a1d[col/8] & MASK(col)) SET_CELL(life,row,col); CLEAR_CELL(life,row,col); TOGGLE_CELL(life,row,col); if (TEST_CELL(temp,col)) { ... }; The Game of Life