C tutorial

download C tutorial

of 42

  • date post

  • Category


  • view

  • download


Embed Size (px)

Transcript of C tutorial

  • 1.A Quick Introduction to C ProgrammingLewis Girod CENS Systems Lab July 5, 2005 http://lecs.cs.ucla.edu/~girod/talks/c-tutorial.ppt 1

2. or,What I wish I had known about Cduring my first summer internshipWith extra info inthe NOTES 2 3. High Level Question: Why is Software Hard?Answer(s): Complexity: Every conditional (if) doubles number of pathsthrough your code, every bit of state doubles possible states Solution: reuse code with functions, avoid duplicate state variables Mutability: Software is easy to change.. Great for rapid fixes ..And rapid breakage .. always one character away from a bug Solution: tidy, readable code, easy to understand by inspection.Avoid code duplication; physically the same logically the same Flexibility: Programming problems can be solved in manydifferent ways. Few hard constraints plenty of rope. Solution: discipline and idioms; dont use all the rope 3 4. Writing and Running Programs #include /* The simplest C Program */ int main(int argc, char **argv) 1. Write text of program (source code) using an editor { printf(Hello Worldn); such as emacs, save as file e.g. my_program.c return 0; } 2. Run the compiler to convert program from source to an executable or binary: $ gcc Wall g my_program.c o my_program$ gcc -Wall g my_program.c o my_programtt.c: In function `main:-Wall g ?tt.c:6: parse error before `xtt.c:5: parm types given both in parmlist andseparatelytt.c:8: `x undeclared (first use in this function) 3-N. Compiler gives errors and warnings; edit sourcett.c:8: (Each undeclared identifier is reported onlyonce file, fix it, and re-compilett.c:8: for each function it appears in.)tt.c:10: warning: control reaches end of non-voidfunctiontt.c: At top level: N. Run it and see if it works tt.c:11: parse error before `return./? $ ./my_programmy_program Hello World What if it doesnt work? $ 4 5. C Syntax and Hello World #include inserts another file. .h files are called header files. They contain stuff needed to interface to libraries and code in other .c files. Can your program haveWhat do the < > more than one .c file?mean?This is a comment. The compiler ignores this.#include The main() function is always/* The simplest C Program */ where your program startsint main(int argc, char **argv)running.{ Blocks of code (lexical printf(Hello Worldn);scopes) are marked by { } return 0;}Return 0 from this functionPrint out a message. n means new line. 5 6. A Quick Digression About the Compiler#include /* The simplest C Program */int main(int argc, char PreprocessCompilation occurs in two steps:**argv){Preprocessing and Compilingprintf(Hello Worldn);return 0;Why ?}__extension__ typedef unsigned long long int In Preprocessing, source code is expanded into a__dev_t;__extension__ typedef unsigned int__uid_t; larger form that is simpler for the compiler to understand. Any line that starts with # is a line__extension__ typedef unsigned int__gid_t;__extension__ typedef unsigned long int __ino_t; that is interpreted by the Preprocessor.__extension__ typedef unsigned long long int__ino64_t;__extension__ typedef unsigned int__nlink_t;__extension__ typedef long int __off_t;__extension__ typedef long long int__off64_t;extern void flockfile (FILE *__stream)extern int ftrylockfile (FILE *__stream);; Include files are pasted in (#include)extern void funlockfile (FILE *__stream)int main(int argc, char **argv); Macros are expanded (#define){printf(Hello Worldn); Comments are stripped out ( /* */ , // )return 0; Continued lines are joined ()} ?my_program The compiler then converts the resulting text intoCompile binary code the CPU can run directly. 6 7. OK, Were Back.. What is a Function?A Function is a series of instructions to run. You pass Arguments to a function and it returns a Value.main() is a Function. Its only special because it always gets called first when you run your program.Return type, or void Function Arguments#include /* The simplest C Program */int main(int argc, char **argv){ Calling a Function: printf() is justanother function, like main(). Its definedprintf(Hello Worldn);for you in a library, a collection ofreturn 0; functions you can call from your program.} Returning a value7 8. What is Memory?Memory is like a big table of numbered Addr Valueslots where bytes can be stored.01The number of a slot is its Address.2One byte Value can be stored in each slot.372?4 H (72)Some logical data values span more than 5 e (101)one slot, like the character string Hellon6 l (108)A Type names a logical meaning to a span7 l (108)of memory. Some simple types are: 8 o (111) a single character (1 slot)9 n (10)charchar an array of 10 characters 10 0 (0)[10] signed 4 byte integer 11 not alwaysint4 byte floating pointfloatsigned 8 byte integer 12 Signed?int64_t8 9. What is a Variable? symbol table?A Variable names a place in memory whereSymbol AddrValueyou store a Value of a certain Type. 0 1You first Define a variable by giving it a 2name and specifying the type, and3optionally an initial value declare vs define?x4 ?y5 e (101)char x;Initial value of x is undefinedchar y=e;6 7 The compiler puts them Initial value 8 somewhere in memory. 9 NameWhat names are legal?1011Type is single character (char)12extern? static? const? 9 10. Multi-byte VariablesDifferent types consume different amountsSymbol Addr Valueof memory. Most architectures store data 0on word boundaries, or even multiples of 1the size of a primitive data type (int, char)2 3char x;char y=e;x 4 ?int z =y 5 e (101)0x01020304; 60x means the constant ispaddingwritten in hex 7 z 8 4 9 3 An int consumes 4 bytes10 211 112 10 11. Lexical Scoping (Returns nothing)void p(char x)Every Variable is Defined within some scope.{A Variable cannot be referenced by name char y;/*p,x */(a.k.a. Symbol) from outside of that scope. /*p,x,y */char z;/*p,x,y,z */}Lexical scopes are defined with curly braces { }. /*p */char z;/*p,z */The scope of Function Arguments is thevoid q(char a)complete body of the function.{ char b;/* p,z,q,a,bThe scope of Variables defined inside a */ char b?function starts at the definition and ends at{the closing brace of the containing blockchar c; /* p,z,q,a,b,c*/ legal? }The scope of Variables defined outside afunction starts at the definition and ends atchar d; /* p,z,q,a,b,d (not c)the end of the file. Called Global Vars.*/}/* p,z,q */ 11 12. Expressions and EvaluationExpressions combine Values using Operators, according to precedence.1 + 2 * 2 1 + 4 5(1 + 2) * 2 3 * 2 6Symbols are evaluated to their Values before being combined.int x=1;int y=2;x + y * y x + 2 * 2 x + 4 1 + 4 5Comparison operators are used to compare values.In C, 0 means false, and any other value means true.int x=4;(x < 5) (4 < 5) (x < 4) (4 < 4) 0((x < 5) || (x < 4)) ( || (x < 4)) Not evaluated becausefirst clause was true 12 13. Comparison and Mathematical Operators== equal to The rules of precedence are clearlygreater than or non-intuitive. When in doubt, add>= greater than or equalparentheses to make it explicit. For!= not equal&& logical andoft-confused cases, the compiler will|| logical or give you a warning Suggest parens!logical notaround do it!+ plus & bitwise- minusandBeware division:* mult | bitwise or If second argument is integer, the/^ bitwisedivide xorresult will be integer (rounded):%~ bitwise5 / 10 0 whereas 5 / 10.0 0.5modulo not > shift rightDont confuse & and &&..1 & 2 0 whereas 1 && 2 13 14. Assignment Operatorsx = y assign y to xx += y assign (x+y) to xx++ post-increment x x -= y assign (x-y) to x++x pre-increment xx *= y assign (x*y) to xx-- post-decrement x x /= y assign (x/y) to x--x pre-decrement xx %= y assign (x%y) to xNote the difference between ++x and x++:int x=5; int x=5;int y; int y;y = ++x; y = x++;/* x == 6, y == 6 */ /* x == 6, y == 5 */Dont confuse = and ==! The compiler will warn suggest parens.int x=5; int x=5;if (x==6) /* false */if (x=6)/* always true{*//* ... */{recommendation} /* x is now 6 *//* x is still 5 */ } /* ... */ 14 15. A More Complex Program: pow#include if statement#include float pow(float x, uint32_t/* if evaluated expression is not 0 */exp)if ( expression ) { {/* then execute this block */ Need braces?/* base case */} if (exp == 0) {else { return 1.0; X?Y:Z}/* otherwise execute this block */} Short-circuit eval? detecting brace errors /* recursive case */return x*pow(x, exp 1);}Tracing pow():int main(int argc, char What does pow(5,0) do?**argv){ What about pow(5,1)?float p;p = pow(10.0, 5); Induction printf(p = %fn, p);return 0;} Challenge: write pow() so it requires log(exp) iterations15 16. The Stack #include Recall lexical scoping. If a variable is valid #include within the scope of a function, what float pow(float x, uint32_thappens when you call that functionexp) {recursively? Is there more than one exp? /* base case */ if (exp == 0) { staticreturn 1.0;Yes. Each function call allocates a stack }Java?frame where Variables within that functions/* recursive case */scope will reside. } return x*pow(x, exp 1); int main(int argc, charfloat x5.0 **argv)uint32_t exp 0 Return 1.0{ float p;float x5.0 p = pow(5.0, 1); printf(p = %fn, p);uint32_t exp 1 Return 5.0return 0; }int argc 1char **argv0x2342float pundefined 5.0 Grows 16 17. Iterative pow(): the while loopOther languages? float pow(float x, uintProblem: recursion eats stack space (in C).exp)Each loop must allocate space for arguments{ int i=0;and local variables, because each new call float result=1.0; while (i < exp) {creates a new scope.result = result * x;i++; }Solution: while loop.} return result;loop:int main(int argc, charif ( condition ) {while ( condition ) **argv)statements ;{ {goto loop;statements ; float p;} } p = pow(10.0, 5); printf(p = %fn, p); return 0; } 17 18. The for loopThe for loop is just shorthand for this while loop structure.float pow(float x, uintfloat pow(float x, uintexp) exp){{float result=1.0;float result=1.0;int i; int i;i=0; fo