12.07.2015 Views

CS 11 C track: lecture 2

CS 11 C track: lecture 2

CS 11 C track: lecture 2

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>CS</strong> <strong>11</strong> C <strong>track</strong>: <strong>lecture</strong> 2n Last week: basics of C programmingn compilationn data types (int, float, double, char, etc.)n operators (+ - * / = == += etc.)n functionsn conditionalsn loopsn preprocessor (#include)


This weeknnnnnnnnPreprocessor (#define)Operators and precedenceTypes and type conversionsFunction prototypesLoops (while, do/while)More on input/output and scanf()CommentingUsing the make program


#define (1)n So far, only preprocessor command we knowis #includen Lots of other ones as welln will see more later in coursen One major one: #definen Used in almost all C header files


#define (2)n #define usually used to define symbolicconstants:#define MAX_LENGTH 100n Then preprocessor substitutes the number100 for MAX_LENGTH everywhere inprogramn NOTE: Just a textual substitution!n no type checking


#define (4)/* That code expands into: */if (i > 100) {printf("Whoa there!\n");}n Note that all occurrences of MAX_LENGTHreplaced with 100n Why not just write 100 in the first place?


#define (5)nnnWhy not just write 100 in the first place?If you decide you want to change MAX_LENGTH toanother number insteadn only have to change one #define statementand all occurrences of MAX_LENGTH will bechanged to the new numberHard-coded numbers like 100 are called magicnumbersn usually repeated many times in a programn would have to change many lines to change thenumber throughout the program


Digression: ? : operatornC has one ternary operator (three arguments),the ? : ("question mark") operatorn Like an if statement that returns a value:int i = 10;int j;j = (i == 10) ? 20 : 5; /* note 3 args *//* "(i == 10) ? 20 : 5" means:* "If i equals 10 then 20 else 5." */nNot used very often


#define macrosn #define can also be used to define shortfunction-like macros e.g.#define MAX(a, b) \(((a) > (b)) ? (a) : (b))n Like a short function that gets expandedeverywhere it's used (a.k.a. an inlinefunction)n But pitfalls exist (won't discuss further)


#define stylen #define defines new meaning for namesn Names that have been defined using#define are conventionally written withALL_CAPITAL_LETTERSn That way, they're easy to identify in coden Conversely, don't use this style for regularvariable names


Operators and precedencennnLow to high precedence:n = (assignment) += -= *= /=n == !=n < >=n + and -n * and /n ++ --15 precedence levels in all!Use ( ) for all non-obvious cases


++ and -- (1)n ++ and -- can be prefix or postfixint a = 0;a++; /* OK */++a; /* OK */n Here they mean the same thing


++ and -- (2)n Prefix is not the same as postfix!int a, b, c;a = 10;b = ++a; /* What is b? *//* <strong>11</strong> */c = a++; /* What is c? *//* <strong>11</strong> */


Types (1)n intn usually 32 bits widen could be 64 (depends on computer)n longn "longer" integern length >= length of intn usually same as intn short (will see later in course)


Types (2)n floatn single-precision approximate realnumbern 32 bits widen doublen double-precisionn 64 bits wide


Type conversions (1)n Converting numbers between typesint i = 10;float f = (float) i;double d = (double) i;n (float) etc. are type conversionoperatorsn Compiler will convert automaticallyn But don’t do it that way!


Type conversions (2)nDangers of implicit conversions:int i, j;double d;i = 3;j = 4;d = i / j; /* d = ? *//* 0.0 */d = ((double) i) / ((double) j);/* d = ? *//* 0.75 */


Function prototypes (1)nnnNormally, functions must be defined before use:int foo(int x) { ... }int bar(int y){return 2 * foo(y);}Couldn’t define bar before fooCompiler isn’t that smart


Function prototypes (2)nnCan get around this with function prototypesConsist of signature of function w/out bodyint foo(int x); /* no body yet. */int bar(int y); /* no body yet. */int bar(int y){return 2 * foo(y); /* OK */}/* Define 'foo' later. */


Function prototypes (3)n Note that foo not defined when bardefinedn Rule of thumb: always write functionprototypes at top of filen That way, can use functions anywhere infile


while loopsnint a = 10;while (a > 0){printf("a = %d\n", a);a--;}Useful when # of iterations not known in advance


Infinite loops and breakint a;while (1) /* or: for (;;) */{scanf("%d ", &a);printf("a = %d\n", a);if (a


More on breakn break exits the nearest enclosing loopn To exit more deeply-nested loops, needgoton Avoid using goto in general


gotofor (i = 0; i < m; i++) {for (j = 0; j < n; j++) {/* code ... */goto out; /* something went wrong */}}out: /* a label *//* continue here */


do/whilenSometimes want to test at end of loop:int i = 10;do{/* try something at least once *//* i gets changed */}while (i > 0);


continuenTo exit a single iteration of a loop early, but keep onexecuting the loop itself, use a continue statementint i;for (i = 0; i < 100; i++) {if (i % 2 == 0)continue;elseprintf("i = %d\n", i)}nHere, only prints out odd numbers


Note on syntaxn Body of for, while, do/while, if, if/else statements can be eithern a block of code (surrounded by curly braces)n a single line of coden Better to always use a block of coden expresses intent more clearly to readern can add extra statements later more easily


Input/output and scanf() (1)n C provides three input/output "files" for youto use:n stdin for input from the terminaln stdout for output to the terminaln stderr for error outputnnormally also outputs to terminaln All defined in stdio.h header file


Input/output and scanf() (2)n printf() function outputs to stdoutn scanf() function reads from stdinn More general versions to read from otherfiles:n fprintf() outputs to any filen fscanf() reads from any file


Input/output and scanf() (3)n fprintf() and stderr used to printerror messages:fprintf(stderr,"something went wrong!\n");nnStill prints to terminalAlways use this for printing error messages orprogram usage messages!


Input/output and scanf() (4)n Recall scanf() function from lab 1nReads in from terminal input (known as stdin)nUses funny syntax e.g.char s[100];scanf("%99s", s);nThis says: "read in a string s that is no more than99 characters long".


Input/output and scanf() (5)nnscanf() changes the variable(s) in its argumentlistscanf() also returns an int valuennnif scanf() was successful, return the number of itemsreadif input unavailable, the special EOF ("end of file")value is returnedEOF is also defined in stdio.h header file


Input/output and scanf() (6)nTesting scanf()'s return value:int val;int result;result = scanf("%d", &val);if (result == EOF){/* print an error message */}


Input/output and scanf() (7)nNotice the &val in the scanf() call:int val, result;result = scanf("%d", &val);nnnnWhat's that all about?Can't explain in detail nowWill explain when we talk about pointersRule: need & for reading int or double, but notstrings


Commenting your code (1)nThe most important thing is to realize thatCOMMENTS ARE VERYVERY IMPORTANT!


Commenting your code (2)n Purposes of comments:n explain how to use your functionsn explain how your functions workn explain anything that's tricky or nonobviousn Who reads the comments?n anyone modifying your coden you, in a few weeks/months/years


Commenting your code (3)nnnnnPut comments right before functionsnnnpurpose of functionwhat arguments meanwhat's returnedComment code that’s not obviousAssume others will read your codeStyle (spelling, grammar) counts!Poor commenting è marks off!


Good commenting/** area: finds area of circle* arguments: r: radius of circle* return value: the computed area*/double area(double r) {double pi = 3.1415926;return (pi * r * r);}


Variable namesnUsually use meaningful variable namesdouble x; /* what does x mean? */double distance; /* better */nNot always necessaryint loop_index; /* bad */int i; /* good */


The make program (1)n make is a program whichn automates compilation of programsn only recompiles files thatnnhave changeddepend on files that have changedn Only really useful for programs withmultiple source code files


The make program (2)nnnnnWrite compilation info in a MakefileUsually compile by typing makeClean up by typing make cleanWe usually supply the MakefileDetails:http://courses.cms.caltech.edu/cs<strong>11</strong>/material/c/mike/misc/make.html


The make program (3)n Trivial Makefile:program: program.ogcc program.o -o programprogram.o: program.c program.hgcc -c program.cclean:rm program.o program


The make program (4)n Targets in redprogram: program.ogcc program.o -o programprogram.o: program.c program.hgcc -c program.cclean:rm program.o program


The make program (5)n Dependencies in greenprogram: program.ogcc program.o -o programprogram.o: program.c program.hgcc -c program.cclean:rm program.o program


The make program (6)n Commands in blueprogram: program.ogcc program.o -o programprogram.o: program.c program.hgcc -c program.cclean:rm program.o program


The make program (7)n If program.c or program.h changesn program.o is now out-of-daten program.o gets recompiled (changes)n program is now out-of-daten program gets recompiledn If multiple .c files exist and only onechanges, only necessary files recompiled


Next weekn Arraysn Stringsn Command-line argumentsn assert

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!