Introduction to C Text: Introduction to Computer Systems : Chapters 11, 12, 14, 13
Problem: Too Many Details For example: Lab 7 Bubble Sort Needed to keep track of too many details! Outer Loop When do I quit? How many times have I been through already? Inner Loop How far am I in the vector? Really, need to pseudo-code! do { ordered=1 for(i=0;i<cnt; i++) { if (VEC[i]>VEC[i+1]) { swap VEC[i], VEC[i+1] ordered=0 } } until (ordered==1)
Problem: Translating from Psuedo-Code Translation is Mechanical, Laborious, and Error-Prone Why not let computer perform translation? Write in Pseudo-Code Allow computer to translate Pseudo-Code to Assembler Pseudo-Code is a High Level Language Translator is a Compiler Example: Bubble Sort in C C code translated to LC3
Origins of C MULTICs operating system MIT / General Electric / Bell Labs Collaboration, 1964 1970 Design an operating system to run GE-645 Main Frame Programmed in Assembler and PL/I BCPL (Basic Combined Programming Language) Martin Richards ( of Cambridge) 1966 Used to write Compilers First use of {}, //, First Hello World No Types (interpretation based on operator)
Origins of C UNIX (1969-1970 s) Operating System Bell Labs PDP-7, PDP-11 B Language (BCPL Lite ) Ken Thompson and Dennis Ritchie Still no types
How C got it s name.
Origins of C B + types + structures = C 1978 The C Programming Language (Kernighan and Ritchie) K&R 1983 ANSI Standard 1988 POSIX standard (libraries) 1990 ISO C89 1999 ISO C99 2011 ISO C11
C Syntax Comments: /* comment */ or // comment to end of line Statement: instruction that ends with a semi-colon White space (blanks, tabs, new-lines) Ignored! (except as a separator between tokens) Not like python, where indentation used to define block structure!
C Functions Functions are the primary building block in C All executable C code is contained in a function To explain functions, we need to know about C types of data
C Types Built-In Integers signed / unsigned char / short / int / long Real Numbers float / double / long double Character (char) void Derived Arrays: <type>[<count>] Pointers: *<type> User Defined: struct / enum / union typedef
LC3 vs.c - Subroutines LC3 - Subroutines PUSH ; put value in R0 on stack ret C - Functions void push(int value) { } group of LC3 instructions args by convention w/ caller return value by convention regs shared with caller memory shared w/ caller group of C statements args specified in function def. return value type in def. no regs variables usually not shared
C Function Conventions Argument list: comma separated list of variables type/names specified in function signature A function works on a copy of the arguments Type of return value specified in function signature A function returns a single value via a return statement exception: void indicates zero values returned Compiler handles the details Argument copying Setting return values in caller Keeping track of return location etc. etc. etc.
The main function Every C program must have a main function When the C program is executed, the main function is invoked Arguments to main yet to come When the main function ends, the C program ends return value of type int is the return code of the program 0 indicates success ~0 indicates some kind of error occurred
Function Signature <return_type> <name> ( <argument_list> ) <return_type> - type of function s return value <name> - Your choice (starting with letter) <argument list> - comma separated list of arguments each argument consists of <type> <argname> int main() int addemup(int a, int b) void print_error_message(int error_type)
Function Declaration vs. Definition Function Declaration <function signature>; Function Definition <function signature> { <function statements> }
Function Statements Variable Declaration: <type> <name> = <initval> Assignment: <lhs> = <expression> Expressions Return: return <expression> Control Statements
LC3 vs. C - Variables LC3 Labeled Words COUNT.fill #3 C Variable Declarations int count=3; everything is 16 bits required initial value program decides type size depends on type optional initial value type must be specified
Variable Declarations <type> <name> =<initial value>; <type> - one of the built-in or derived type names <name> - your choice starts with letter, no embedded blanks =<initial value> is optional int count=17; float area=2.89; int vec[10]; int *vec_ptr;
Function Statements - Assignment <left_hand_side> = <expression>; <left_hand_side> or <LHS> - Something that can be assigned to <expression> - Something that can be evaluated Expression is evaluated, and the result is copied to the <LHS> count = 12; first_initial= T ; area = height * width; take_off_time=(now + delta)%24; distance = sqroot(x*x + y*y);
C Expressions - Constants <constant> Decimal Integers: <digits> e.g. 0, 123, 82, Octal Integers: 0<digits> e.g. 07612 Hexadecimal Integers: 0x<digits> e.g. 0xFA3B, 0x00a1 Floating Point numbers: <digits>.<digits>[e<digits>] e.g. 1.0, 3.141, 6.23e23, Single characters: <char> e.g. a, 3 List of characters: <chars> e.g. this is a test.
C Expressions: Variables <variable_name> The value of any variable argument local variable global variable
C Expressions: Unary Operators <UnaryOp> <expression> Operators with a single argument Invert: ~,! Sign: +, - Increment/Decrement: ++, -- Side effects Prefix vs. Postfix Address/Pointer: @, * Casting : (<type>) ~flags,!empty +12, -num count++, blocks-- ++count, count++ @vec /* like lea vec */, *num_ptr (int) first_initial
C Expressions: Parenthesis (<expression>) Evaluate what is inside parenthesis before using that value Remove ambiguity e.g. - - x vs. ( - x)
C Expressions: Binary Operators <expression> <BinOp> <expression> Arithmetic: +, -, *, /, %, ** a+b, time%24 Relational: <, <=, ==, >=, >,!= WARNING: = is assignment!!!!! Logical: &,, ^, &&, a>b, count <= max (a>b)&&(a>c) Shift: <<, >> a<<2 /* fast a*4 */
C Expressions: Ternary Operator <Condition>?<T_expression>:<F_expression> Evaluates <Condition> If <Condition> is true, returns <T_expression> If <Condition> is false, returns <F_expression> (x>y)? is greater than : is less than or equal to
C Truth Value In C, any value OTHER THAN zero is Logically True In C, a value of zero is Logically False (blocks_left)? There are blocks left : There are no blocks left Question: What is blocks_left==-7?
C Expression: Function Invocation <function_name>(<function_arguments>) Invokes function with arguments specified arguments may be epxressions evaluated before function invoked Function s return value becomes the value of the expression
C blocks List of statements surrounded by curly braces {} A block is treated as a single statement For example, a function definition is a function signature followed by a C statement that defines what that function does. However, the C statement is almost always replaced by a block of statements Modern C compilers require a block of statements for a function definition
C Control Statements If/Then/Else if (<condition>) <then-statement>; if (<condition>) <then-statement>; else <else-statement>; Evaluate condition far enough to determine truth value if the condition is true, execute the <then-statement> if the condition is false, execute the <else-statement> (if present) if (a>0) a--; else a++;
C Control Statements While loop while <condition> <loop_statement>; Evaluate condition If condition is true, execute <loop_statement>, then re-execute loop. while(i>0) sum+=a[i--];
C control Statements Do / While loop do <loop-statement>; while ( <condition> ); Execute loop statement then test <condition> if true, reexecute loop statement do resetarray(i++); while(i<array_size);
C Control Statements For loops for(<init>;<condition>;<increment>) <loop_statement>; Execute <init> statement Test <condition> if true, execute <loop_statement>, then execute <increment> statement, then test condition again for(i=0; i<max; i++) array[i]=0;
C Function Statements: return return <expression> ; Evaluates <expression> Returns the value of the expression to the caller
Example C code int bignuff(int n) { if (n>10) return 1; return 0; } int add3(int n) { n=n+3; return n; } int main() { int x=5; return (bignuff(add3(add3(x)))?0:x; }