Digital PDFs
Documents
Guest
Register
Log In
EY-1925E-H0-2
2000
134 pages
Original
11MB
view
download
OCR Version
7.1MB
view
download
Document:
Programming in C
Order Number:
EY-1925E-H0
Revision:
2
Pages:
134
Original Filename:
OCR Text
PROGRAMMING Digital TIN Equipment Educational EY-1925E-HO-0002 C Corporation Services Second Edition, August 1985 The information in this document is subject to change without notice and should not be construed as a commitment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors that may appear in this document. The software described in this document is furnished under a license and may be used or copied only in accordance with the terms of such license. Digital Equipment Corporation assumes no responsibility for the use or reliability. of its software on equipment that is not supplied by DIGITAL. Copyright © 1985 Digital Equipment Corporation. All rights reserved. Portions of this text are based on LEARNING TO PROGRAM IN C, a book by Thomas Plum, copyright 1983, Plum Hall inc. and on the course C PRO- GRAMMING WORKSHOP, written by Thomas Plum, copyright 1983 by Plum Hall, Inc. The following are trademarks of Digital Equipment Corporation: ALL-IN-1 DNC BAL-8 DNC CDP EduSystem PRO/NAPLPS PRO/RMS - PRO/Videotex COMPUTER LAB FLIP CHIP PROSE COMSYST FOCAL COMTEX GLC-8 QUICKPOINT RAD-8 CTBUS IAS Rainbow DATATRIEVE IDAC ReGIS DDT IDACS RSTS DEC IDAC RSX DECCOM KA10 RT-11 DECgraph KL10 RTM DECmail LAB-K SABR DECmate MASSBUS Tool Kit DECnet OMNIBUS TYPESET-8 DECspell OS 8 TYPESET-10 DECsystem-10 PDP TYPESET-11 DECSYSTEM-20 PDT ULTRIX DECtape PHA UNIBUS DECUS PS 8 VAX DECWORD P/OS VMS DECwriter Professional VT PRO/BASIC VAX VTX PRO/FMS Programming in C ~outline- - page Programming in C Course TEXT: "Learning to Program by Thomas Qutline in C" Plum, Plum Hall Inc. Monday: Introduction to C C C Operands and Control Flow Operators - if, else C Control - if, switch, while, for Tuesday: Flow comma, do while, break, goto C Functions The C Preprocessor Wednesday: C Pointers The C and Arrays Library - to - and to and including array arguments including sprintf and sscanf Thursday: Structures and Unions - to and including pointers to structures The C Library - File I/0 C Pointers and Arrays - pointer C Pointers and Arrays functions - cmd arrays Friday: The C Library Structures - system and Unions level - line I/0, arrays of args, heap pointers to allocation structures, unions 1 Programming in C -outline- page 2 TEXT ASSIGNMENTS It is recommended that the following reading in the text "Learning to Program in C" be performed and the questions Programming exercises are provided in that reading answered. at the end of this workbook as a replacement for those in the text. Monday : Optional assignment - computer concepts (as needed) - Chs. 1, 2.1 "Learning to Program in C" "Learning to Program in C" 2.6, 3.4, 2.7, 3.5, "Learning to Program in C" Sections Sections 2.8 3.6 Tuesday: Sections Sections 3.8, 5.4, 3.9, 5.7 to Program in C" 3.11 Wednesday: "Learning Section Sections 3.12 7.2, 7.4 Thursday: "Learning to Program Sections Sections Friday: (or following "Learning the 7.3, 8.1, 7.7 8.2, 8.6 completion to Program Ch. in C" in C" 6 "Programming in C Workbook" Ch. 9 of the course) Programming prage ~outline- in C TABLE OF CONTENTS intro Y C&: s & & ® ® @& ® & © 2 & ®© © » B L o & € & H © e 6 & @ & @ © 8 v O & mat 18 W}l’y C s ® & ©® © © ® ©° B & & & & 5 & S @ S & o B S & & @ ¢ & & & 5 © ¢ o 6 e ©& 8 O A quick overview..... Identifiers, keywords, comments, constants. ® Data Lypes. .o ® ® » 6 ® © 6 © ®© 6 & » @& o & & & 0 e » o i it ottt ecessooscsososse Compile and execute a simple C progranm. A program to copy input to output...... A program to count lines, word, chars. Sample formats for printf............. ® input....... [ L4 ® [4 [2 & [4 L4 ® ® 12 14 15 ® Buffering of 11 13 |4 ® 10 .4 ® 16 17 operands Data 18 19 types....ceveenen Constants............. String Relational operators.. Expressions, Logical Type 20 constants...... Declarations.......... Arithmetic operators.. ® ® g [ 4 operators, ® & [ e ® ® % & & © & [ 3 and operands operators......c.cceeieeveeesen ConversionsS. ...c.oceeeeessecees Type conversion examples and cast. Lvalue and rvalue......ceeeoeeessase increment and decrement operators. ® 21 22 23 24 25 26 27 28 .4 29 Arr Ay S. it ieeessosoaossssonsssssess Arrays of characters............ 30 31 The array indexing formula...... String functions.....cceceeveeee Bitwise operators. ...ccev v vvesss Bitwise "right rotate" function. Assignment operators.......cec.. Operator precedence......ccesooesseee The conditional operator (thenelse) 32 L 4 & @ Lg & 33 34 36 37 38 40 3 - Programming in C -outline- page TABLE OF CONTENTS (continued) control Statements If (else) Else if Switch and blocks.. statement...... statement....... While and Comma operator......... Do while for 41 & statement.... & k4 £ 14 42 43 44 L3 statements. 45 46 statement..... 47 Break and continue..... Goto statement......... 48 49 @ functions What is a function@?.... Basic function syntax.. Non-integer functions.. Argument passing....... Recursive functions.... L] & & o ® ® @ [ & L4 & & ® © o ¢ & 50 51 52 [ & & L2 L3 e e ® 53 55 Initializing automatic scalars. Storage class....cco... 56 57 Static storage class... Initializing arravs.... External variables..... 60 61 Register storage class. ® » ® & ® L4 ® & 4 @ ® & & ® ® @ -4 ] @ & & 58 @ & -4 L4 L 2 & & |4 B @ 62 ocope rules.....c.coc00 0 Initialization summary..... 63 o4 Empty brackets: three cases Passes of C compiler....... 65 ® & ® 66 preprocessor DefineabfifiQDQQQOD&Ofiflfiw Define and macros...... & @ 67 68 IncludQDODfibebeofibfiblbb 70 Conditional compilation. Llneoeoo»»ooaflnosoocpeoo 71 & & 73 4 Programming in C page -outline- TABLE OF CONTENTS (continued) pointers What is a pointer?......cccvievenns Declaring and using pointers.......... Simple examples using pointers........ Pointers as function arguments: swap.. Pointers as function arguments: Pointers 74 75 76 o 77 @ 78 79 scanf. and arraysS. ..o ceeeooooncoss Pointer and array examples: Array arguments: Array arguments: hex.c, 81 index.c. strcpy, strncpy........ read.....c.cceescoeoee Array arguments: write........ccooeeee Pointer arithmetic........ccict e csnss 82 84 ® 85 ® 86 87 Multidimensional arrays.....ccceeevesss Pointer aArrayS...ceceeceoocsccsscsscsees Command line arguments to C........c.c.. Variable number of function arguments: Pointers to functions.......oev v 88 89 91 92 structures Structure basiCS. .. .vv v veeronsoseas Members of structures......ccceeceeeoeos Members and nesting. ......cceoeceeceeceos Defined types for structures.......... Pointers to structures......ccceeeeonoe Formats for structure definitions..... UNions. ¢ v voeeeeeeeeeseoeceoosssssocnsoescs Typedef ... ittt neseennsencnnscen Arrays of structures........ceceeveees Bit fields....eeeeeteeeeeooeosnsoconos Linked 1lists.....vcuoceeececcescsssocescs 93 94 95 96 97 99 .100 L4 @ . 101 .102 .104 .106 5 Programming in C -outline- TABLE OF CONTENTS Clibrary standard input, Character standard input/output: output, (continued) and getchar, page standard error..... 108 putchar.........cccece.. 109 Line input/output: gets, puts........ ittt eecerocconsee 110 output: printf . ... ie ettt eececoecsenecnnses 111 Formatted input: scanf.....cee e eeeeescescescooosonsonoes 112 Formatted 1/0 to and from strings: sprintf, sscanf.........cccc... 113 File I/70. ... et ietieeeooeosoossossonassocssssossecscssss 114 Example of File I/0... .t eeeeeeoeeesonoseoosocccoocnsnoe 116 Error output: System 1evel perror, fprintf.... ...ttt eecocennn 117 I/0. ...t eeeeeneeeeeoeensosoenonnonsoness 118 L Heap 120 allocation: malloc, free.......oi ettt veceeconenees 121 style Data and variables. . ... it ittt eneeetnoneensononnnss 122 Operators. ...ceeeen.s s s s s s s e e s s s Control structures.......c.. FUNCEIONS. .t it i i it Common € e s s e e e e e s e e seaeeneesene 123 ittt eeoeeesoeonsannones 124 ittt ittt ittt DUGS . ottt i et ittt ts ct et oneesonsesansononess 125 e enensenscesonesesoneesnos 126 labs Monday Programming Assignments........oeeeeereenesooncen 128 Tuesday Programming Assignments.......c..eeeeeerceoooooss 129 Wednesday Programming Assignments.........oeeveeeeonsess 130 Thursday Programming AsSsignments.......veeeeeeeeoeonesns 131 Friday Programming Assignments. . ......ooeeeeeeeoncoonones 132 b 0021 Ox11l | ———— dc?2 0022 Ox12 dc3 0023 O0x13 dc4 nak 0024 0025 Ox14 Ox15 syn 0026 Ox16 etb 0027 Ox17 can 0030 Ox18 em 0031 0x19 sub 0032 Oxla esc 0033 Ox1b fs 0034 Oxlc ags 0035 0036 Ox1d Oxle 0037 Ox1lf 0040 0041 0x20 Ox21 OTADI 0042 Ox22 0043 O0x23 0044 0x24 Ox25 | | TVGIINS | MO | SN | MT——— L, | AN I MEGITY | WAL | ORI H M RN ¥~ | N ORI, YDA, ST A GG ST 0045 0046 0047 0050 0x28 0051 00572 O0x29 Ox26 O0x27 0x2a 54 55 0066 0067 0x36 Ox37 56 0070 0x38 57 0071 0x39 58 00772 Ox3a 59 60 0073 0x3b 0074 Ox3c 6l 0075 Ox3d 62 63 64 0076 Ox3e 0077 0100 Ox3f 0x40 65 0101 Ox41 66 0102 Ox42 67 0103 0x43 68 0104 Ox44 69 70 0105 71 0107 0x45 0x46 Ox47 712 0110 0111 0x48 0x49 73 0106 74 0112 Ox4da 75 0113 Ox4b 76 0114 Ox4c 77 0115 Ox4d 78 0lle Ox4de 79 0117 Ox4f 80 0120 0x50 81 82 0121 0122 0x51 0x52 83 0123 0x53 84 85 0124 0125 0x54 0x55 S< G Dled ~ MIN O~ Wt 0x35 - A - ToOetne om0 I N e S O 0065 R RWUWHEIDTOHRDDLAO DD VA dcl 53 TR QTDOITE Ox0f 0x10 0064 0x33 0x34 C B 0020 | ST WM M. 0017 I | TN SR, | SO si dle Ox32 Y S Ox0e 00672 0063 octal, N 0016 50 51 52 page lid— SO P 0x0d Ox31 U 0015 0061 OO0 cr np 49 <moaN | SN —————tws v 0013 0014 0x30 S vt O0x0a Ox0b Ox0c 0060 GO mchonts SR 0x09 00172 fimaramn roeboL | SO 0011 nl Ox2f 48 DY e Ox07 0x08 | _———— ht 0007 0010 Ox2d Ox2e 477 0055 0056 0057 e bel_ bs 45 46 i wEROSTTD | 0x06 Ox2c NI 0006 Ox2b 0054 ot Samdvmen. GRS WRESES RGN WIS Ox04 0x05 0053 | acOROMED eavicim | SCRGINE OCRNEWS 0004 0005 OB eot eng decimal, 43 SGOMEEAR SRS AN O0x02 O0x03 ASCII, 44 SR, | COMSUIN | SHOINON | BT O0x01 ST SO Ox00 Ty e - O 0000 0001 0002 0003 ack -outline- characters: S At ormery oarnin ww o ASCTI WN stx etx of C IO U oo wowomi soh ctmire | o nul somm— Table in NIy Programming del hexadecimal 86 0126 0x56 87 0127 Ox57 88 89 0x58 0x59 90 0130 0131 01372 91 0133 0x5b 92 0134 O0x5c¢ Oxba 93 0135 0x5d 94 Oxbe 95 0136 0137 96 0140 Ox60 97 Ox61 0x62 Ox5f 98 0141 01472 99 0143 0x63 100 0144 Ox64 0x65 101 0145 102 0146 103 0147 0x66 Ox67 104 0150 Ox68 105 0151 0152 0153 Oxba 0x6b 106 107 0x69 108 0154 Ox6bcC 109 0155 Ox6d 110 0156 Oxb6e 111 0157 Ox6f 112 113 0160 Olel O0x70 Ox71 114 0162 115 116 0163 0164 0x72 Ox73 Ox74 117 0165 0x75 118 0166 119 0le7 O0x76 Ox77 120 0170 O0x78 121 122 0171 0x79 0172 Ox7a 123 0173 0x7b 124 125 0174 0175 Ox7c Ox7d 126 0176 Ox7e 127 0177 Ox7f 7 Programming in C -intro- o A general purpose o Low -- level "portable Can access No storage Weak No programming many I/0 Cannot language. assembler" computer allocation typing page objects or directly. heap mechanism. rules. facilities. access composite o) Single thread control O Minimal run @) Modern machines: time Byte as flow environment addressing Address Stack objects is similar cheap to integer a whole. 8 in C -intro- o g Programming o Efficient code a variety of generation on modern machines. UNIX consists of 12,000 of C and 800 lines of assembler language. C o on a variety of machines. Portable Both the compiler and the library are easily ported to o is lines Easy to other learn machines. and use. page 9 Programming in C -intro- page A guick overview Fundamental data characters, types: integers, Composite data types: pointers, arrays, and floatings. structures, unions, functions. Flow control: if, Recursion while, and of switch. 'for | to a function or or global within a file, or global free’: storage. data: internal do, reentrancy automatic ocope for, through all files. Weakly typed: many data permitted. conversions block, 10 Identifiers, o) | -intro- Programming in C kevwords, comments, page 11 constants Identifiers are strings of letters beginning with letter. and digits, Upper and lower case are distinct. (including underscore) Variables must be declared before use. First eight characters are significant (less for externals) Names that start with underscore should be reserved for o) Keywords system programs (reserved): auto | break case char continue default do o Comments between double else entry extern float for goto Constants: 0 Separators: O 1 ;{1 and */ 3.07 | "'x '’ = ( ) Whitespace: blank or newline or horizontal tab, (Whitesmiths: any other non-printing character.) (@ static struct switch typedef union unsigned while consist of any text /* o , | if int long - register return short sizeof Suggestion: 80-character line limit. “help" Programming in C -intro- Data Bytes page types Type Description char a single byte. short a short integer. int an integer (same size as integer. long a long float a single precision floating point double pointer). number. a double precision | floating point number. 12 Programming in Compile C -intro- and execute a page 13 simple C program main() { printf("this is 3 To run using the O EDITING S vi a C program.\n"); UNIX operating svstem: myprog.c i{new text)>ESC insert a{new new text (before append new text (after e W . text>ESC move cursor) cursor) cursor left one column one line move cursor down move cursor up move cursor right one line one column "gobble" character under cursor write output file and quit s Wq COMPILING & LINKING $ CC -0 Myprog myprog.c RUNNING PROGRAM $ myprog run using the VMS EDITING s operating system: EDIT MYPROG.C AC arrow keys delete key key (CTRL-Z>EX PF2 to enter character mode to move cursor on screen to delete to get to characters help exit on editor using keypad COMPILING $ CC/LIST MYPROG ¢ PRINT MYPROG listing file object file to get hard MYPROG.LIS MYPROG.OBJ copy of listing LINKING $ $ ASSIGN SYSSLIBRARY:CRTLIB.OLB LNKSLIBRARY ASSIGN SYSSLIBRARY:VAXCRTL.OLB LNKSLIBRARY $ LINK MYPROG RUNNING PROGRAM $ RUN MYPROG image file MYPROG.EXE V1.0 V2.0 file FProgramming in C -intro- A program to copy copy input to output {(stdio.h> #include /* page 14 input output to x/ main() { char c = c¢; getchar(); while (c != EOF) { putchar(c); ¢ = getchar(); } exit (0); /*exit (1) in VAX-11C*/ 3 At the top of each #include source file that performs 1/0 {(stdio.h> defines: EOF -1 getchar () putcha() r Programming in C -intro- A program to count #include <{(stdio.h> /% lines, count words, lines, chars - page words, in chars input * / main() { int inword; short nc; short nl; short nw; char c¢; inword nc = = nl while /* /* /* /* currently in a word? number of chars */ number of lines */ number of words */ /* most recently read: */ char or EOF */ NO; = ((c nw = = 0; getchar()) != EOF) { ++nc; if (¢ == '"\n’) ++nl; if (¢ == " " inword || ¢ == = NO; "\n' || else if (inword == NO) { inword = YES; ++nw; 3 } printf("%d exit 3 (0); | %d %d\n", nl, /*exit(l) nw, nc); 1in VAX-11C+*/ ¢ == "\t") 15 Programming in C -intro- Sample Integer formats for | page printf tyvpes %d integer %X hex %0 octal %030 3-digit %C ASCII (printed decimal, signed) integer integer octal integer with 0-fill character otrings of characters %S ASCII character %.5s A maximum string (null-terminated) of 5 ASCII characters from a string fixed-point, 8 wide, 2 -2345.78 Floating point %8.2f %12.5e e-format: -2.45678e-12 places: 16 page 17 ~intro- Programming in C Buffering of input On most systems, input from terminals is buffered one line This allows correction of typing mistakes on at a time. that line. one Thus, the program does not see the input until the newline (Each operating system has its own method of is typed. over-riding this buffering to allow a program to see each character as typed.) EXAMPLE <{(stdio.h> #include /* copy input to output */ main() { char c¢; c = getchar(); while (¢ != EOF) | { putchar(c); c = getchar(); } 3 THIS WILL HAPPEN S program dog and cat dog and cat | THIS WILL NOT HAPPEN | § program ddoogg aanndd ccaatt Programming in C -operands- Data o The fundamental char short o C page types data types : : a a byte. 'short’ 'long’ are: integer long : a float : single-precision. integer double : int : bits bits 32 bits bits double-precision. 64 bits a 16 or pointer | 8 16 32 (address) 32 Signed/Unsigned short unsigned 0o ' short range of values range of values unsigned long unsigned int num; ab; unsigned char x; Defined data types #define tiny tiny -32768 0 -> -> +32767 65535 char x; unsigned tiny vy; #define ushort #define bool Advantages to unsigned short int defined data types: semantic distinctions portable data (different different enhance readability defines - hardware) bits 18 Programming in C -operands- page 19 Constants O Character one constants: char within single quotes le' 0 f\tl’ I\nf’ I\lOl Integer constants: decimal: 142, octal: 17, | 34721 a leading zero indicates an octal 042, hexadecimal: Oxo6f, 01, 0732 constant, a leading 0x indicates hex constant, 0x238, 0xl1l7 integer constants are represented in int (on PDP - 0 . 200000L 1is (2/4 bytes) long constant) Floating constants: 1.23 .23 1.00 17e~-23 floating constants are represented in double (8B bytes) Programming in C -operands- page String constants String constants: characters 0 "Hi 0 Stored o] By convention, is written within double there" the in memory as null the array last character, of chars. character of a string ‘'\0’. QUESTIONS: 0 What is the Hhelloll o quotes: What is size of 58 the 80 these two _ difference between strings? 20 page 21 -operands - Programming in C Declarations ) Variables must be declared before use. 0 Declarations specify a type, followed by a list of things having that b, short a, char gq, o) - r, type: c; sC1001; The most readable format is an alphabetized list, one variable per short line, i; with a comment: /* buffer index counter #*/ int more; /* is there more data? * / char tbufl801; /* terminal I/0 buffer */ double x; /* the unknown A/ Programming in ~operands- C Arithmetic /, % 5 % 2 = 4 % 2 = o 3 Co operators (remainder) % gives remainder; a gives page the % b remainder of dividing a by b. Not valid for double, float. * and / and % have higher precedence + and - Unary - has higher any of the precedence of funca() call than above. No guarantee could than a(), evaluation + funcb() b(), or X + (y+z) (x+y) + z X & (y*z) (x*y) * z L - - L ad sequence: * funcc() c() first. (X + z) +y (x *~ z) *y Compiler can rearrange across these parentheses. Parentheses are not adequate for specifying the Allows optimization: order of calculation. (x + Value 1) + of: (y + 2) Dbecomes X +y 23 +4 % - 6 -5 +1 % + 3 22 Programming in C -operands- Relational The relational > of lower >= 0 (is or Assignment (and not are 1 result operator of x lower + 1 (not equal) (0=FALSE, still precendence (y Previously we 1=TRUE) lower precedence than operators. + 2 wrote: while ((c while (¢ = getchar()) = EOF) not: Always QUESTIONS: is != (assignment) arithmetic why are: equal) relational): = All are: (= precedence == produce operators operators ( page = getchar() parenthesize What 1s embedded the value L 3 == § 1 >= 0 4 ) 4 of: != EOF) assignments. 23 Programming in C -operands- Expressions, o) Operators: o Operands operators, Expression operand 0 upon): 1234 ‘x’ OxFF X n C (examples): operator unary-operator o operands (the data being operated constant variable o] and page operand operand X + 1 n -40 * &X constant 40 variable ‘0 X n Subexpression = an expression that operator + A operand X 46 expression y+2 x=(y+2)*46 subexpression v+2 46 a larger expression X = z) (y + * is part 46 of 2 24 Programming in C ~pperands- Logical O O o) logical means means operators && (and) || I (or) (pipe (negation) Precedence of Both have && y € (7 ¢ ||. than relational operators: 2 (zero) into YES (one). MAX && ((c=getchar()) != '\n’)) Sequence guarantees in C: full-expr (@ of "Short-circuit": qguarantee left-right sequence, stop evaluating when result is determined: if 0 than that Negation is monadic (unary): takes one operand. Converts YES (non-zero) into NO (zero), NO o] characters) (exclamation point) && greater (y NO (FALSE) YES (TRUE) are lower precedence Xx O operators "semi-Boolean": Zero non-zero The page 25 && | ] (more Truth Table DO WS N M D ARG SN DY OESEY N A SR R STNSD MWD GKEN GLGR WSS SO WMRW Sher wC GRS M NN RS SO VR S to come...) Programming in C -operands- Tvpe 1) Widening of conversions operands Register Operands page "int" ("coercion"): sizes: 2-byte (16 bit): PDP-11, 8080, %80, 4-byte 68000, (32 shorter bit): than int are loaded VAX, into ... int-sized temporaries. long remains float 2) Type operands coercion, the other, unsigned * are loaded if one operand temporaries. 4 unsigned long * unsigned operand is "slightly wider" A 1int, unsigned double float * unsigned short short char char int, to than equal than size. signed. machine *# * unsigned widened 4-byte long int, smaller further double * is is machine means double it float * into balancing: After 2-byte long-size. int, unsigned long unsigned short short unsigned char char a preferred type for this machine architecture. long 26 Programming O in C -operands- Type conversion For assignments, is converted to examples the the and right type page cast side Value the left of side. short 1i; tiny t; float O Types f; i=¢t; /% t is sign t =1; /* t gets f =1i; /4 i is converted to i = /* £ is truncated %/ coerced by using a f; can be extended low-order byte cast. short i; double d o) From Standard = 4; sqrt((double) library: sqrt() #*/ i); */ float */ 27 Programming in C -operands- Lvalue o lvalue has: type, storage A simple - case of an | class, lvalue name, is an location. identifier. 'Right hand side of an assignment may be any object that has an rvalue if it An A o rvalue Left side of an assignment is an object with a location in storage. This object is called an lvalue. An o and page a value. This object is not an 1lvalue. rvalue has: type, name, simple case of an rvalue is 4 I 0 = O a constant. simply fetches ¥; x; Which of ] < QUESTIONS : = called value. Making a value from an lvalue its value from its location. X is /* legal /* illegal the */ */ following are lvalues? 28 page 29 -operands - Programming in C increment and decrement operators adds one to a variable (lvalue). O 44 O ++ or -- used before the name subtracts one from a variable. -— (prefix): = a; .. e..++b. b value of expression is a + 1 ++ or -- used after the name (postfix): b = a; @ @ 0b++0 & & value o) Fill o expression is a in the missing parts: short o of x, v; x = 0; Yy = X++; /% y == */ y = ++x; /* y == _*/ of ++, --. Do not rely on exact sCi++1 sCi++1 sCil = = = time It will be done by the next sequence-guarantee point. tLj++1; tCLid; tLi++]; /* GOOD */ /* BAD 4/ /* BAD 4/ Simpler rule: if you increment or decrement a variable, do not refer to it again in that statement. Programming in C ~operands- page Arravs A o composite The data declaration: short declares o o] type scoresC3071; that scores A declaration char msgl801]; name is: msqg type is: char(801] of "sandwich" 30 short of integers. type + name. Arrays are subscripted starting at zero (just like birthdays and anniversaries!) To initialize for The o) an array contains a scoresl0l1, o) is (i=0 for scoresCl], the array ; i{(30 ; scoresli] ... scores([29] scores to zero: ++i) = 0; statement‘used above: init: i=0 - done test: i(30 - if body: scoreslil step: ++1 - prepare scoreslLil] is an = lvalue. once YES, before do loop body and step 0; for next test 30 Programming in C -operands- Arrays page of characters o) Strings are o By convention, the null character, '\0’, whose value | zero, 1s put on the end of all strings. This eliminates the need to store string lengths. @ For the Ial’ o) represented string Ipl' "april", Irl' Iil' Programs which build ‘A0’ to those in C as the C lll’ I\OI arrays compliler strings must append strings. | of characters. generates: is 31 Programming | | CLEE in C The array indexing formula char sC5121; “type" | | EETD U R SR sC0J Basic EAD AEDO ~operands- | | Aes CORE GO GES WOED sCll THITD l l QRSO OBMD GNP DR N0 e 'page of s | ' ! | eAIe sC2] - is: char[512] s[5111 indexing formula: address of jth element = address J * of (size zero-th element of + each element) QUESTIONS: Suppose &sLC01 = What is Suppose a short and is 2000 (monadic &sC10137? declared: al5121; &al01 = 4000 What is &alC10137? "&" means address-of ) 32 Programming in C -operands- page String functions cpyastr #include s2, 3); | === | | ===~ l <{(stdio.h> /*cpyastr * / cpyastr (sl, - copy a (sl, s2, char slC1]; char s2C1; unsigned int string from s2 to sl n) /*destination string*/ /*input string*/ /*number of characters n; to | copy*/ { short for 1; (i=0 ; i<n slCil 0 Manipulation of In standard C, o) Alternative for = = ++1) s20iJ; strings must be done explicitly. no statement will process an aggregate. to above: (i=0 slCidl ; ; ; i<=n '\0‘; && (sllCil = s2Ci]) /Anull body/ = '"\N0’ ; ++i) 33 Programming in C -operands- Bitwise & bitwise and page 34 operators (bit-and) & | 0 1 ...' ___________ 0 0 1] 0 1 ()] 0 1 0] l | bitwise or (bit—or) ......,...! uuuuuuuuuuu 0] 0 1 1] 1 1 ~ | 0 1 | ~ bitwise exclusive or ...' ........... 0] | 1| o] o] Example: char x = 0 1 1 0 0x16; x & OxF 0 0010110 00001111 x 1 00010110 0 000O0O0O0O1 | What is the difference between && and & 7? 2 1 is QUESTIONS: && What 1 2 are O0x3F O0x3F the 0x67 | Ox67 & values 1 is of the O following expressions? Programming -operands- in C Bitwise operators page 35 (continued) unary ones complement (< QUESTION: 5 ~“0 1is OxFFFF or 0177777 ~1 1is OxFFFE or 0177776 ~ bitwise left bitwise right 007 << 07 >> What 2> 2 (bit-not) && is the 07 shift & (zero fill) shift value 010 16 bit (signed fill) of: machine Programming in C -operands- Bitwise Right rotate "right - rotate" bits function shifted off rolled Example using 8 bits: /* right rotate into page the to the right are to be left function */ short rightrot (n, b) short n; /* short 16 bit word to rotate /* number to b>0 ; --b) . 01) b; { for of bits . ( { if ; (n & /* n = (((unsigned)n n = ((unsigned)n repeat >> 1) else »>> 1); 3 return (n); 1 0 Always parenthesize bitwise expressions; bitwise precedence is tricky. */ rotate | b %/ times #*/ 0100000); 36 Programming in C ~operands- Assignment 0 Expressions X = of X can be written X o 2; in the compressed form; 2; 5; /* X *= Z; /* multiply x times /=y - 1; subtract 5 from x */ z /* x gets divided by */ (y - 1) j1 + n; */ operators: + o form; X -= x 0 += operators - the + page - A&/ % DO &N Usefulness: all00 can be ~ i + j1 = afl00 i + §1 += n; * i + written: all00 * all0o0 *~ i +'j] is evaluated only oncel 0 The form += is preferred to the consider 0 #define tiny form =+ x=-1; char tiny x, y: X o) += y; /* Expression result converted to type not widened to int #*/ is value from operation, of left-hand side. 37 Programming in C -operands- Operator precedence a+ Db o o Which binds more % ¢ tightly, By historical agreement, O Fully parenthsized: 0 Or, in words, a + "multiply b QUESTION: Put into words (a + b) - * ¢ + d the + or the #*7? c, then add a"” the * (b * c) times page 38 Programming in C -operands- page 39 Table of precedence Precedence Level Operators 15 () 14 I 13 + | 10 ¢ 9 == 8 & 7 A 6 l 5 && 4 | 3 ? 2 = 1 ’ ++ . -- - (type) (etc., op=) (K (= > = |I= += =-= Qu ! x.. > show the binding: P i to | Parenthesize W >> < 11 "3 Y -> /% 12 QUESTIONS: €31 * & Programming The 0 in C - conditional —-operands- operator page (thenelse) The ’‘'thenelse’ "7?:" operator provides a conditional expression in C. | o) Ternary o if (g > (triadic) operator: takes three operands. 25) X = z2; X = Vy; else rewritten: X 0 = q > 25 -x : ? Examples: absx - minxy = = x 0 7? x (y ?2x x; :V; yA : y A T ] is 40 Pregramming in C -control- Statements 0 An expression makes a page and blocks plus a semi-colon statement. ++X; o) c getchar(); X + 1; Curly braces denote { a block /% useless (compound { = V; 3 0 Null one statement: lonely a statementx/ 3} ++]; X but semicolon statement) 41 Programming in C -control- If o) if (else) page 472 statement (expression) 0 non-0 =) => FALSE TRUE statementl +— | | e else statement?2 +- 0 | ~+ Statement can be if simple or (i<4) xCil compound if = 1i; (1<4) B! yCil = 1i; ' xCil = 1i; yL£il = 1i; 3 o] The if else (i if = clause is associated with the closest un-elsed 0) | (bC3jil == bLil = if if statement. (i 0) 0) { 1; if else printf 1= ("error\n"); (bLjl == bLild = 0) 1; 3 else printf O Always put braces around a nested if. ("error\n"); -control- Programming in C page Else if statement o) if (exprl) statementl else if (expr?2) statement? else if (expr3) statement3 else ~default statement 0 Last else o) only one statement is executed QUESTION: clause is optional. What does this program print? for (i = 8; ++i) 1 (= (i ¢ 4) printf ("A"); else if (i % 2 == 0) printf("“B"); else if (5 < 1) printf ("C"); 1; { if else printf ("D"); 3 putchar(’'\n’); 43 Programming in C -control- Switch 0 page statement Example: switch (cmdchar) { case ‘a’: add(nl); break: case ‘d’: delete(nl, n2); break; case ‘c¢c’: change(nl, n2); break:; default: remark("?", break: ""): 3 o) Execution whose starts at the case label constant is equal to the expression, and continues til the of the o} Default o You switch, is should Prefer the next end break. optional. always switch after e) or each escape case the with a break. switch to elseif unless different conditions sequence. are tested or tests must be in 44 Programming in C -control- statements while and for O while page 45 (expr) statement 0 test is at top of the loop o for (exprl; expri; eXpr3) statement same as expr 1; while (expr2) { statement expr 3; 3 o) Use for rather than while when: loop to be performed a known number of times is there O "Endless" loop #define FOREVER loop initialization FOREVER { wait 1 sec print time 3 for (;;) Programming in C . -control- Comma j=k, Complete left list page 46 operator num=1i++, Evaluated | ct=1++; to of right. sequence-guarantee full-expression {3 && | | ’ Function to reverse a string in place ("SPOON" int reverse char sLC1; becomes "NOOPS") (s) { char t:; short i, for 7J; (i=0, j = t = sCild, strlen (s) sCild = - 1 sCj1 ; i<(j , ; sCLjl1 ++i, = t; --7) Programming in C -control- Do while | statement statement while (expr); o test at bottom o) The do while of the loop statement is desirable only when the problem dictates that statement be executed at least once. do { printf ("Answer ans y = getchar(); while (getchar() or n: "); != '\n’) != 'n’); 4 3 while (ans != 'y’ && ans page 47 Programming in C -control- Break and O Break causes from for, an continue early while, while do, exit or switch. (expr) { statement if (expr) break: statement 3} O N + 1/2-time loop FOREVER { statement(s) if (expr) break; statement(s) } Continue o) statement Continue of the while causes for, the next while, or do. (expr) { statement if (expr) continue; statement 3 iteration page 48 Programming in C -control- Goto o) Goto is o goto label; page 49 statement never needed. label: o for (...) for (...) for (f..) if (error) goto error: /*code to fix the errorx/ error; Programming in C ~-functions- What e is subl.c imain() | subl () | | i | subl(arg) | eee | sub2(arg) page sub2.0 -lc a function? pgm. C ... , ... sub2.c | | | sub2() | ... | l mmmmemme- l e | compile compile compile only only only linker executable program VMS ULTRIX $ CC PGM % cc -c pgm.cC s CC SUB1 % cc -c subl.c s CC SUB2 % cc -c sub2.c s LINK PGM,SUB1,SUB2 % 1d pgm.o subl.o 50 -functions- Programming in C Basic function return x to /* pow - - page 51 syntax the power y */ double pow(x, y) /* base */ double x; /* exponent */ long y; body -——- return ( ... name [return typeld ); ([Cparmlistl) Cparmlist declarationsl; { body } 0 More power and complexity than a single statement. O independent building block o) Take time to become familiar with existing libraries, o) default return type is to avoid re-inventing the wheel. reverse char (s) sC1; { 3 "int" Programming in C -functions- Non-integer o Function must #include be page functions declared in the calling function <(stdio.h> main() { short i, convert(): long j; i = convert (j); 3 short convert (num) long num; o) If a function return integer is assumed. is not declared o The return statement will be converted to expression the type of the QUESTION: function. What is convert convert(j) the data type of 52 Argument /* test page 53 -functions- Programming in C passing integer power function </ main() { short 1i; short power(); for (i = 0; i ¢ 10; ++1i) printf("%d %d\n", i, power(2, 1i)); 3 AUTOMATIC STORAGE i | t O | | 2 | t I | | 0 | | l copy of variable o PARAMETER STACK Precise usages of i ==)> parameter the terms called function: formal parameter, parameter, real lst param stack "argument" In calling function: actual parameter, actual dummy argument; In (- and argument, formal argument, argument; "parameter": Programming in C -functions- Argument /* power - raise passing integer x page (continued) to integer n-th power * / short int power(x, n) x; short /*base*/ n; / *exponent*/ { short p; for p=1 ( ; n p‘ * = > 0; --n) X; return(p); 3 | l X actual Always What widened does ~ aria before arguments the - as to sta : we int, k | l | | | in parameter long, or double. look like as we P ek o asm de o e stack: s ter & enter the Pt T AN IR SRS w0 A after UMD power T call: ARENNS QUESTION: | | | n Width of STACK SHECTGES o) | | PARAMETER WY P STORAGE N AUTOMATIC 54 Programming in C -functions- Recursive #include page functions {(stdio.h> main() { long factorial(); printf exit ("3 factorial is %d\n", factorial (3)); (0); 3 /* factorial - return n! A / long factorial(n) long n; /* parameter, local storage */ £ if (n (= 1) return (1) return (n else * factorial(n - } o) Variables declared within a function are local to that function and come into being with the dynamic invocation of the function. They disappear at function termination. parameter stack comes into being with the dynamic invocation of the function. It disappears at function termination. 1)): 55 Programming in C -functions- Initializing automatic 0 An "initializer" of Automatic arrays scalars may be an automatic page attached scalar CAN be (but to not initialized the declaration an array). in VAX-11C. main() £ char ¢ = 'x’; short i = 1; short j = 1 & printf("%d exit 2; %d %c\n", i, j, c); (0):; 3 QUESTION: o What The does this intialization executed each program print? is done time the by instructions function is that entered. main() { short receipt(); printf ("First = printf("Second exit %d\n", = %d\n", (0); ] a short receipt() { short return number = 1; (number++) ; 3 QUESTION: What does this program print? receipt()); receipt()); are 56 -functions- Programming in C Storage 0 page 57 class Picture of C program in computer memory contains the machine instructions for DATA STACK the program contains variables which remain in FIXED locations -- "static" storage contains automatic variables arguments, and function-call bookkeeping; changes as functions are called and returned Programming in C -functions- Static o) Internal storage page class static: Declared inside a function or block, and is known only inside otays put; Remembers that is block not values in between Initialization is is the loaded into (private the memory). stack. function done only machlne once, calls. when the main() short receipt():; printf ("First = %d\n", receipt()); printf("Second = %d\n", receipt()); exit (0); 3 short receipt() { static short return (number++) ; number = 1: } QUESTION: What is the output of this program? program 58 Programming in C Static O -functions- storage class page (continued) External static: Data that is common (global) to several functions Declared OUTSIDE the body of any function Shared by all source file #include functions that follow rand that {(stdio.h> static Short rnum = 0; /* in - */ return a /* random number */ random short integer | short rand() { rnum | = rnum return (rnum } * 12047 >> + 13911; /*period=8192+*/ 1); | ; /* srand - set random seed x / int | srand(seed) short seed; { rnum = seed; 3 QUESTION: In which memory DATA, or STACK? TEXT, segment does rnum reside: 59 Programming in C -functions- | page Initializing arrays 0 UNIX = static arrays automatic o - VMS static at o) data be initialized link initialized is initialized into the program file time static short static char If initialized cannot both static and automatic arrays can be o can be arrays digits(101 = {0,1,2,3,4,5,6,7,8,93; = "hello, world"; msglfl3] the array bound is bigger than the number of initializers, the extra elements are initialized to zero. - If If QUESTION: the array bound is less initializers, a compiler no bound is given, of initializers. What are the it than the number of error is generated. is taken to be intial values? static char st[(51 =:"std"; static char sC21 = static short al51 static short bLC1 static char xC1 the number = = = | l "abc'; ' {1, 33; {1, 2, 3, "abc"; 5, 73; I | l | I | I I I | I I | | l | 60 Programming in C ~-functions- - External 0 data that is page 61 variables common declared outside (global) to several functions the body of any function functions that wish to share access to external data use the #include extern keyword (stdio.h> short a = 0; /*external data can be main() { extern short a; short 1 = 17; long 1; 1 = subfn (i); if (a (= 25) 3 long subfn (arg) short arg; { extern short a / = 32 a; arg; ;ééurn ( ... )3 I I initializedx/ Programming in C -functions- Register o) register storage class int x; data will be allocated instead of reduce page 62 in general purpose registers, memory execution time since a memory access is not needed for variables that are used often, eg. loop index VAX-11C will ignore - it will choose which variables to place o] into registers Register storage class may be assigned to formal parameters in a function or to automatic variables. int power(x, register int n) x, n; { register int p; } o) Cannot take address of (&) register. o] For maximum portability, register should be used only with int and pointer wvariables. However, most compilers will do sensible things with char and short register declarations, also. he X Programming in C -functions- Scope Internal data o) page 63 rules§ (local) data declared inside a function is known only within that 0 | function data can be declared inside any compound statement (formed with curly braces) data declared block in a block is (BLOCK) known only within | that main() {0 short i: if (i <= 25) { float i = 1i; 3el0; 3 | External data 3 (global) 0 data declared outside the body of a function in a source file is known to all functions that follow in that source file o) static data declared outside in a source in any 0 other non-static function function keyword 0 file canNOT be source the body of a function made known to a function file data declared outside the body of a in a source file is made known to any in any source file with the extern Function_names are external by default. Programming in C -functions- Initialization Scalars - - or once, constant short lim = BUFSIZ + 1; char separator = ‘\n’; static Arrays 64 summary initialized to constants expressions: static 1initialized to lists of constants, padded with zeros: static short static char buflC5121 static char arC51 sC] = = {1, = 2, 3, 4, 53; {01; "dog&cat"; Auto storage (stack), and register storage (register) are initialized every time the function is entered. Scalars - short = b initialized a + to expressions: 1; register int ¢ Arrays - cannot be — can be initialized = 326 buf [31 char msgll = short tim[5] = b; in "dog"; y 2, in auto auto storage storage (UNIX) (VMS) with irregularities {'d’',’0o’,'g’}; - char / initialized some i o page External or static storage is initialized only into the program file at link time. They stay put in fixed locations. pan' O | 33; /*legal*/ /*illegal - compiler errork/ /A*NOT padded with zeroes*/ Programming in C ~-functions- Empty brackets: 1) three page cases in C As parameter to function, TP IO they are a synonym for address 2) long setstr char slC1]; (s) | (-- receives the address of array With array initializer, they mean "take the size from the count static of initializers." short xC 1 = {0123, 0456, 07773; | 3 3) s With an external array, they mean "the bound will be specified by the actual data declaration” extern short y[];‘ 65 Programming in C -functions- Passes page 66 of C compiler o) Preprocessor: expand macros, compile-time constants, #include files, and conditional compilation O Parser: translate program‘into a logical o) Code generator: translate - assembler code o Assembler: O tree-structure Linker: produce language this relocatable tree into object from the symbolic assembler link the relocatable code together with other code code object object files Programming in C -preprocessor- page 67 Define o #define the ID token-string preprocessor replaces all occurences of ID with 'token-string’ after this defining instance. ‘token-string’ is scanned for previously defined ID’s. O Example #define FAIL #def ine EOF if (EOF == getchar()) exit (FAIL); becomes if o) (-1 1 -1 (in-line == getchar()) exit(1l); Dangerous example: #define RABBIT O Define Style (RABBIT # RABBIT) can also be done cc 0 code) -DRT1l=1 rules: put # in on command line in UNIX pgm.c column use uppercase put all 1 names #defines before any data declarations Programming in C ~preprocessor- Define 0 Example and macros (macro): #define SQUARE(n) #include (stdio.h> n *n main() { char x[1001; short i:; y ® = & SQUARE(xLil); @ 3 becomes (in-line code): v *~ = x(ild xCil; QUESTION: Write the in-line code for SQUARE(x+1). Fix the definition. page 68 page 69 -preprocessor- Programming in C Macros (continuéd) < (x)) & (y)) 2 (y) #define MAX(X, V) (((x) g#define MIN(x, ) (((x)< (y)) 2 (x) = (y)) #define ABS(x) (((x) ¢ 0) ? -(x) : (x)) "Generic"” - accept any data type Efficiency - in-line code, no call and return Preprocessor lines are taken one at a time; they can be continued by placing a '\’ at the end of the line. (((x) < (y)) 2 \ #define MIN(x, y) (x) : (y)) Continuation possible for any C statement static char msgll = "very long... \ line"; But if string fits on one line, prefer static char msgll = "very long ... line” Don’t put side-effects on arguments ABS(++n) SUGGESTION: ==> (((++n) < 0) ? -(++n) : (++n)) Write function first. Make macro only when needed. (Function is less prone to programming errors.) Undef - To remove the latest definition: #undef id Rarely used in practical programming. Programming in C -preprocessor - page Include ®) #include Causes with "filename" this the line entire to be file replaced ‘filename’ F'or personal or project header files The (1) (2) (3) UNIX compiler the directory searches containing the C progranm, directories specified in the compile command, "standard places." The VAX-11C compiler searches (1) the current default directory (2) the directory containing the C program @ #include <filename> For system-wide header The UNIX compiler searches dlrectorles specified in "standard places." (1) (2) files the compile command The VAX-11C (1) O compiler searches SYSSLIBRARY - a standard directory Header file.h o) files are usually named: where Includes may be nested file is any filename. (discouraged). 70 Programming in C ~preprocessor- Conditional #if page 71 compilation constant-expression or #ifdef ID or #ifndef ID (any C or preprocessor statements) #else (any C or preprocessor statements) #endif #if constant-expression is true if constant-expression evaluates #ifdef #ifndef ID is to nonzero true if 'ID’ has been defined. ID is true if ‘'ID’ has not been defined. Programming 0 in C -preprocessor- Conditional compilation examples Env1ronment dependencies #ifdef USHORT #define ushort #else #def ine ushort #endif 0 Simulating hardware page (adapted unsigned from stdtyp. h) short short on mainframe #ifdef UNIX static static char buffer [481C801 = char *bufp = &buffer; O0; #else static char #bufp = 0x8000; #endif 0 Safe | way to /* nest #include "sandwich" around header */ #ifndef SOMENAME ... text of header #endif o ~ "Tuning" for size #if MAXTOKEN < 128 #define TOKEN char #else #define TOKEN ushort #endif o Including TRYOUT main with function ... (code for function) #ifdef file TRYOQUT main() { (code 1 #endif to test function) 72 Programming in C -preprocessor- page Line 0 | #line line-number ID can be used to reset the line-number and/or ID which is passed to the compiler. /*test.c - 0 and o are mixed up in string name */ main() { char ® & s0 [£251; 9 strcpy (so, "test string"); 3 % cc test.c "test.c", /*test.c line 23: so undefined - 0 and o are mixed up in string name #line used to change compiler error msg * / | main() { char s0 #line 37 COPY strcpy [£251; (so, "test string"); 3 % cc COPY, test.c line 37: so undefined 73 Programming in C -pointers- What o A pointer another o) a holds pointer? the address of variable. short 1, short *p; j; i = 0; O is page /* 1, j are short */ /* p is a pointer to short */ of (&) */ | p = &i; /* p gets j = *p; /* that address which is i pointed to by p*/ thus: p;&i’jzkp; is the same as: j = 1i; o short #*p; is read "declare declaration of p as a short the variable pointer" p J = *pi is read "set assigning #p @ has 2 the to that which variable is pointed to lvalues, j meanings "Address-of" (&) can not QUESTION: j Which of the be applied only rvalues. following are p = &i; p = &(>(1i + 1); p = &(i = 1); ILLEGAL? to 74 Programming in C -pointers- page 75 Declaring and using pointers O short #pi, *pj, long *pl; double *pd; 0 pi, pl, pd are the pointers; they are lvalues. *pi, *pl, *pd are references to the objects pointed to; variable t; they are also address 1100 /*pi,pj are pointers to short/ /*pl is pointer to long*/ /*pd is pointer to double*/ contents | 9 ! | | pi 1300 | 1100 | t 1350 | 14 | ‘ I I | | 20 | | 1380 | Pj | 1350 | pl 1400 1410 | l | | 1410 | | l | 7 l 1430 1440 | | | | 0.0 ! pd lvalues. | | 1430 | Programming in C Simple examples short *pi, *pj, long *pl; double *pd; pi using pointers t; 1) *pd += *pi; 2) pi 3) Api = 4pl; 4) Pj = pi; 5) *pJ /= 3; 6) ++pJ; 7) (Apj)++; 8) ++pl; = /*pil,pj 1is 1s /*pl /*pd &t; 1100 | 9 1300 |” 1100 1350 14 20 PJ 1380 | 1350 pl 1400 | 1410 1410 | 1430 | 1440 | pd page -pointers- 1430 are pointers to short*/ pointer to longx/ pointer to doublex*/ 76 Programming in C Pointers 0 page ~pointers- as function arguments: swap Call by value; C cannot directly alter function arguments in caller. To change the arguments in the caller, pass pointers int badswap(i, short i, { i ] 3 j) to be altered. int swap(pi, short js short t to the variables #*pi, pj) *pj; ghort t; t; t 1; = *pi; *pl = *pj; *pj = t; J; t; 3 This simply changes the local i and j. This is called: swap(&x, &vy); pi pj 77 Programming in C -pointers- | Pointers as function arguments: int page scanf x; short float y; z; nargs = scanf ("%dxhd%f", &x, &y, &z); Reads from standard input: 368 23 87.62 nargs tells how many successful assignments. separators are whitespace: spaces, tabs, newlines Input Use this call: FFFF7421 scanf ( "%8x", &status) 8-digit hex ABC | int number ,sCanf("%c%c%c", &cl, &c2, &c3) Three A BC scanf ("%$s%s%s", hello scanf ("%s", contiguous characters sl, s2, s3) Three separate characters (into strings) str) One | "word" (delimited by whitespace) hello scanf ("%80c", str) At 499.95 scanf ("%3hd.%2hd", most &dols, Dollars o) Using of scanf, characters there up to 1s no a 80 characters str ¢s) and simple way newline. into cents to (2 shorts) read one line 78 Programming in C -pointers- page 79 Pointers and arrays @ All operations done by array subscripting can be done - usually faster - with pointers. short gLl1001]; short *pq; pq = &qL01; /* pg gets address of the zeroeth element of gq */ equivalent is P9 = 4; to /*q 700 q equivalent to &qLO01*/ 1200 |- ===~ | | 5 | | =-==- | | 10 | i | | | Pq | -——-- ] 495 | --=-- | | | | ----- | 1300 i | ~===~ e | is | ~==-- | | I | ===-- | | |-=--- | o 0 o) If we then write: What does i have type of g = tvpe of glnl i in = *pq; it? = »Declaration: short gL100] is read Expression: qlnl "array of is 100 read shorts"” "q sub n" Programming in C -pointers- Pointers O Whenever and arrays o) (con‘t.) are used in arithmetic integer constants and variables scaled by the storage double *pd; short *pi; + 2); /* the 2 /% d = *(pd - 7); /* /* Example: &gC31 g+ 3 &qlC31 gqCL31 0 size of the pointer. e.qg.: X = x(pi o] page pointers expressions, are » Generally is 2 the 7 is 8 first multiplied by (the size of a */ short) */ first multiplied by */ (the size of a double) */ short ql(51; - is is is 1200 + 1200 g + + gqL01 gCll | | | ————| | | qC21 | qgC31 | | | - === 1206 gf4l | 1208 342 3%2 3 1is (g + - glnl 3) is *(g + n) | ===~ | | === | 1200 1202 1204 80 page 81 -pointers- Programming in C Pointer and array examples: index.c /* index - return index of first occurrence of char ¢ * * - in string s SUBSCRIPTED version * / | {(stdio.h> #include int index(s, c¢) /*string to be searchedx*/ /*search character*/ char sC1; char c¢; { short 1 while (sCil = 0; = ‘'\0’ && sCild == ¢ 2 1 != c) ++1; return (sCil : -1); } /* index - return index of first occurrence of char c in string s POINTER version * * - * / ({(stdio.h> #include int index(s, c¢) char *s; char c; /*string to be searched*/ / *search characterx/ { char *s0 while = (*s s; != '"\0’ && #s ¢ s = c) ++S; return } (#s == 7?2 - s0 : -1}); Programming in C -pointers- Array arguments: 0 | page strncpy When arrays are passed to functions, what C really passes is a pointer to the array. /* strncpy - copy n characters string sl from string s2 */ char *strncpy(sl, char *#sl, unsigned s2, n) *s2; int n; { char *oldp = sl; “while (n-- > 0) = Aksl++ return *s52++; (oldp); 3 o) strncpy will accept (1) calls: strncpy(al, a2, DIM); or where al (2) strncpy(&allf0l1, &a2001, and a2 are arrays: char 0 QUESTION: sl strncpy What declared as allDIMl, is the a2CDIM1; type of DIM); to Programming in C -pointers- Array QUESTION: Assume just arguments: the before a | question following machine calling ADDRESS STORAGE line 800 | a | | 1800 What does the strncpy(save, T B T T S2 R e sl What when save |l parameter stack look line, 4) is entered? | l ! | l ! (- 1lst does the storage strncpy returns? 1800 of state strncpy(save, VARIABLE save page x line, b | l l |y | 4) ¢ | \0O | I 2z | | w | like when param save 1look like | | g | | 83 -pointers- Programming in C Array arguments: read {(stdio. h> #include /* read */ page - unsigned read int char sC1; unsigned int characters read (s, into an array n) /* where to store the bytes /* max no. of bytes to read n; { int 1i; char c¢; for (i = 0; 1 < n; ) { getchar(); C if (c == EOF) return sCi++]d if (¢ = == (i); c; '"\n’) return (i) ; 3 return ( i); 3 EXAMPLE read S (array, 10) I 4 ® (- lst param n char sC1; IS REWRITTEN BY C TO BECOME: char +*s; (A POINTER TO CHARACTERS) read #*/ %/ 84 Programming in C -pointers- Array arguments: /* write - write the page write characters from an array A/ unsigned char int write int n; (s, s(C1; unsigned n) /* location of bytes to write /* how many bytes to write */ */ Snsigned int j; for (j = 0; j < n; ++3) putchar(sCjl); return (n):; 3 QUESTION: What does the parameter stack look like after following function ("0", up their 1lst param (- 1lst param TG MNEION SIS MRS "o (- 1) I ONDIRE "abc" arguments? 3) CUPARNT write ("abc", set EAOTD write calls 400 | 3 500 ! | ! | | 0 ! o’ the \NO ! | | | 85 Programming in C -pointers- page 86 Pointer arithmetic O o) o o) Adding or subtracting pointers and will cause C to scale according to storage size pointed to. | integers the Pointers may be subtracted from each other (scaled). Pointers to like types may be meaningfully compared with each other. Pointers may be assigned or compared against 0. C guarantees char if (p that no data item will ever be at 0. *p; == NULL) return; o NULL: QUESTION: in - stdio.h If &sCO1 == 1000, what address will receive 7777 short *ptr; char slL201; ptr = s; A(ptr+3) = 777; Programming in C -pointers- Multidimensional static short , arrays scoresC71[91 { o, 1, o0, 2, o0, 0, O, O, 1, o, o, 0, 0, 0, 0, 0O, 0O, O, o, o, 0, 1, 0, 0, O, 0, O, O, o, 2, 3,1, o, 7, 0, o0, 0, 0, 0, 0, 0, O, O, O, O, ll 0’ 1' Of O' OI 0! 2, 3, l’ 1, OI 0, o0, 0, O, O, O, }; 0 Arrays are subscripts stored in rows, that vary the fastest. scores L[21C31 o is, = sizeof (scores) = 7 x 9 sizeof (scores[01) = 9 x 2 sizeof (scoresC01L01) = 2 = shortl[9] tyvype QUESTIONS : of scoresl(2] If right &scoresCO01C0] == 1200, x 2 what is &scores[11L01] scores(1] o] Passing a multidimensional X where = sumup sumup(scores, is short short short array to a function: 7); declared sumup(arr, arrl1[9]; nrows; nrows) page 87 Programming in C | | ~pointers- Pointer 0 o 0 short ~ arrays #aptrl103]; declares aptr pointers to to be short. an array static char *citiesC1 {HNYN’ "PHILA", cities 1000 | | N 1103 | | P QUESTION: | B H | 1113 | | ] l 0 | | | | \O | | I | l O i L Write down citiesC21C21 &cities[21C21 xcitieslC2] | ! i 1113 Y | | A | | l | | L | S t | | \O NULL}; | | || | 1109 | ten | 1109 | | 1100 | | i "LA", 1103 ! of = HBOSH’ l 1100 page 88 | | \0 A | | | | | the TYPE and VALUE of \0 | Programming in C -pointers- Command line arguments When main() is called it page to C is passed two arguments: main (ac, av) unsigned int char *avLl1l; ac is passed the count of to the main. av is a pointer the number to a One ULTRIX interface cmd al a?2 avC0] avlCl]l avlL2] avLC 3] list of name pointers. types: VMS interface cmd al 1400 1404 av of arguments cmd = and the program sees ac ac; "Ssys$login:cmd.exe" a2 the following variables: l 3 | } 1440 : I | 1440 1662 1662 l 1444 1448 1666 1669 1666 1669 { a ! 1 ! \0 : E a E 2 ; \0 E 1452 c | m | d | \0 | | 89 Programming in C -pointers- Using arguments #include {(stdio.h> main(ac, av) unsigned int char in v page 90 echo.c ac; *avL1]; | { short 1i; for (i = 1; i ¢ ac; printf(i ¢ ac-1 ? ++i) "%s " : "%s\n", avlil); ~exit (0); 3 o Example S echo ab ac 2200 av 2204 xyz | 12345 | | | ___ l 3750 | e | c : 2630 : avC0l 2630 | 3750 | | h | o | \O | avCll avl2] avL31 avL41 2634 2638 2642 2644 : 3755 : 3755 : a : b : \ 0 : | : 3758 : 3758 { X : y : y/ : \0 | : 3762 : 3762 { 1 : 2 : 3 : & | 5 | \O | : 0 :. i | Programming in Variable C -pointers- number of Taking the address to walk this list: functi on arguments: of char *cpystr(olddest, char #*olddest; char +*s; the argument char for e (src — a pointer olddest I 4 w— s != NULL; src Src (#Asrc = A++ps) ‘A0") *de st++ Adest allows *src; ApsS; while list cpystr s) { char **ps = &s; register char *dest register page | ksrc++; ‘A0’ ; return (olddest):; 3 Walking call the the pointer ps al ong the arguments allow user function with vari able number of arguments: cpystr(target, olddest 1300 | "ab" 2000] 1304 | 3000] 1308 3“55;5| 1312 | 31301 1316 :—-_5_: , "C“’ 2000 3000 3050 3130 | ===~ | | l src | dest ; “““““ ; | : A D | ~===m | NULL); a | b e| | \0| | === | | ===~ | ps lldefl’ | ~===m- | | ¢ | \O] | === - | | === | | d | e | \O] to 91 Programming in C -pointers- Pointers 0 0 page to functions Funcfiions themselves cannot be directly manipulated but can be. pointers to the functions void f(g) void (*qg)(); k = /* pointer (*g)(i); to function */ /* call g(i) */ } O For example: short fnl (arg) short /xthe first function/ arg; { ' if (arg < 5) return else return (11); short fn2 short arg; - (arqg) (10); /*the second function*/ { if (arg < 5) return else return (21); (20); 3 int func short short (g, i) /*the calling function*/ (4g)(); 1i; | { printf ("%d\n", (*g)(i)); 3 main() o~ { func (fnl, 7); /* will print 11 */ func (fn2, 3); /% will print 20 */ 92 Programming in C -structures- page Structure basics o) A structure is a group of variables, which 1is placed together 0 for ease of varying type, of manipulation. - Formal definition§of structure variable (define struct the pattern) task { char job [201; char *plan; short start; float length; 3; 0 Declare structure variables (actually allocate struct task e job N from the pattern storage) B t; e e+ T A R A A I I A I O et it ettt P + plan | start I e ——— + | | +———t-——+ length | | +—-————- + o o) struct task ti, tj, tk; declares three variables: on VAX: sizeof (ti) = ti, tj, tk. (bytes). 93 Programming in C -structures- Members o) of page 94 structures The member of a structure is used in expressions: structurename.member . e.qg. t.plan or tk.length 0 o) element type t.job t.plan t.start t.length char [£201] char * short float offset in structure 0 20 24 26 EXAMPLE: in task.h header struct file: task { char job [201; char #*plan; short start; float length; }; in prog.c #include #include program file: "task.h" {(stdio.h> main() { static struct task tl = {"Hawaii vacation", "car-plane", 1210, 8.451; printf ("%s %s %d %8.2f", tl.job, tl.plan, tl.start, } tl.length); . Programming in C -structures- Members and nesting ) structure.member is an lvalue Examples: if (tj.start ( ti.start) tk.lengtfi.; 12.3; tl.plan 0 = ptr; One structure may be nested inside another. struct time { char hh; char mm; char ss; }; struct task { char job [C20]; char *plan; struct time start; float length; }; struct o) We task t; can now reference the t.start.hh t.start.mm t.start.ss components of each time: page 95 Programming in C -structures- Defined o types structures the structure as Common usage #define 0 for page a new variable EXAMPLE : in task.h header #define TASK TASK file: struct task { char job char *plan; short float [201; start; length; }; in prog.c #include #include program file: "task.h" <(stdio.h> main() { static TASK tl = {"Hawaii wvacation", "car-plane", 1210, 8.453; printf ("%s %s %d %8.2f", tl.job, tl.plan, tl.start, 3 tl.length); 96 Programming in C ~gstructures- Pointers o] structures Only a few operators are allowed upon structures: t.plan member &t address-of sizeof (t) Structures e.qg. o) to page ti size of cannot be operated upon as a unit = tj; / *generally not workx/ /* but works in VAX-11Cx/ The declaration: struct task #*ptask; declares ptask to point to a structure of type task. ptask = &t; o) To access members pointed of the structure to by ptask: ptask->job or ptask->plan or ptask->start.mm 0 ptask->length is the same as (Aptask) . length 0 t.plan is the same as (&t)->plan 97 Programming in C ~-structures- Pointers o) to Pointers structures to structures structures 0 to page (continued) are often used to pass functions. EXAMPLE: /*function to add a task A/ #include int structure ‘ "task.h" install struct (ptask) task *ptask; { ptask->job ... ptask->plan ... ptask->start.mm return (...); } called from the main() num = install by: (&ti); ... to a task table 98 Programming in C ®) -structures- Formats for struct task { structure char page definitions STRUCTURE FORM and ACTUAL STRUCTURES *desc; long plan; } tskl, ) struct tsk?2: task { char . STRUCTURE FORM only *desc; long plan; }; ®) struct ACTUAL STRUCTURES only ACTUAL STRUCTURES from { char *desc:; long plan; } o) struct tskl, tsk?2:; task tskl,tsk2; a previously defined STRUCTURE FORM 99 Programming in C -structures- - page 100 Unions 0 structure-like objects O o variable One variables, of varying values i.e. types overlay one (not follow one another use: two or more ways and widths in one variable another as of in a structure) looking at the same storage. union { long 1; char clC41; parts; } 1 and ¢ are can be held two objects which in the variable parts. If = parts.l then o) 0x87654321 parts.cL0] parts.clfl] parts.cl2] = = = 0x21 0x43 0x65 parts.clL3]1 = 0x87 Another use:§saving space in data storage by using the same space for mutually-exclusive values. union payeeno { char ssnoll21; char taxidnoll1l51; 3 o) 0 A union will be large enough to hold the Alignment will satisfy all uses. It is the track of programmers how the recently used. task union was to keep most largest member. Programming in C -structures- page Typedef o) Typedef is a method of for of language not part the C types. creating synonyms This preprocessor. o) Instead of: #define bool We could say: typedef o) typedef int int bool; char *STRING; STRING s, t; is of part the 101 Programming in C -structures- Arrays of Consider the problem structures of looking up a keyword in a predefined table and mapping it into an integer "token" for the 1 o) book 2 is 3 on 4 In header file struct page this 5 efficiency. desk 6 (token.h) keytab { char *word:; int token:; };: word | l l token | | 0 In program: static struct keytab dtabll { "define", 1, "include", 2, "undef ", 3, "line", 4, "ifdef", 5, "ifndef", 6, "endif", "elseif", }; 7, 8, = 102 Programming in C Arrays ~structures- of structures page 103 (continued) /*function to lookup a keyword in a table of keytab structures and return the token A/ '"token.h" #include int lookup (keyword, table, char *keyword; struct keytab #table; short tablesize; tablesize) / *keyword to lookupk/ /*ptr to table of structures*/ /*number of entries in tablex/ { for ( ; tablesize if > 0 ; (cmpstr(keyword, return return 3 0 Called from main() typ = | +---—-- + | | | 4————- + tablesize| | == + /*failurex/ as: dtab, 8); 1 | 1 | n | e | \0OJ o -+ +——— - + 4 4+ table->word)) o - -+ Q +————— + table ++table) (table->token); (0); lookup("line", -+ keyword | --tablesize, Ie bttt + >l | m——— | |1 | | -===- | | e e | £ ] 1| n| e | e \0Of + e e - +- ——————— >l |----- ] d A i ln] e | 1 jlul|l d]| e | \O| ee - -+ | 2 | | ===~ | | | | i | === —- | | | = ; | T+ - >l 8 | e | 1 | s | e | 1| £ | \OJ| e+ Programming in C -structures- Bit 0 Represent o Useful Useful o page fields data as bit field instead if storage is limited for defining status words, #define bits struct flags unsigned of bytes hardware int { bits alloc:1; type:3; ref:2; sc:3; bits bits bits }; struct flags 104 f; FEach individual field is and may be referenced: n bits long f.alloc or f.sc etc. SC ref type alloc interfaces, Programming in C -structures- Bit O fields f.alloc turn = = 0; test: if (f.sc == e o Can‘t 0 Unnamed 0 Field on 0 Do not Do next to not of (&) field. are used for 0 alignment causes padding. is overlap unsigned boundary; aligned at depend varies 1) @ unsigned. cannot field left o fields of width Fields it @ take address the the 0 1; off: f.type to page (continued) To set oh: to | the on allocation between machines. right, combine mask-and-shift not right bit-field to next unsigned. order within word; (some CPUs order bits left as in VAX, PDP) operations operations. and 105 Programming in C -structures- Linked 0 A slight the of struct linked of our lists task task { char *plan; short start; float }; task t; length; structure (chains) struct task *next; char 7jobl[201; struct 106 lists re-definition creation page of will tasks: allow Programming in C -structures- Linked o) list struct task struct task #*p; page (continued) *tlist; To add an element to a task /* point to /* point to new task linked current head list: p = malloc(sizeof (struct task)); p->next O = tlist, tlist = p; To delete an element from a task linked list: p = tlist, free(p); tlist 107 = p-J>next; */ */ Programming Standard in C input, ~-Clibrary- standard stdin Standard input stdout Standard output stderr Standard error o These three output, and page standard error file files are already opened for the main program. o) The default for all three files is the interactive terminal. | ~ === | l stdin | terminal-----=--==~-- > stdout |- > | | cmd | | l terminal | i | stderr | | - === > terminal | ====--- | 0 The | stdin and stdout can be individual commands changed VMS for UNIX ASSIGN filel ASSIGN file2 RUN CMD SYSSINPUT SYSsOUTPUT cmd <{filel | -=—===- l stdin file 1 i l -——=--=—-eu-- > | | l stdout | === > | cmd | | l >file2 stderr file 2 108 Programming in C Character 'o -Clibrary- Input/Output: page 109 getchar, putchar Basic'I/O facility: read a character at a time from the "standard" input write a character at a time to the "standard" output 0 Get a character from the standard input: char getchar() getchar gets a character from stdin. (c >= 0) getchar returns EOF (-1) on end of file. o) Put a character to the char standard output putchar(c) putchar puts character ¢ to stdout, returns c. (c must be >=0). putchar returns EOF on error. o File copy: while ((c = getchar()) != EOF) putchar(c); o getchar and putchar are typically implemented as macros, not functions. | Programming in C Line -Clibrary- Input/Output: gets, gets - gets a text line from puts - puts a text line to o | char stdout. ‘'\0’' 0 terminator newline is returns from string at (a) (b) gets stdin. characters character The puts *gets(s) copies A - s, stdin to newline EOF is added. deleted. its argument. int puts(s) copies from character string at to stdout, appending a newline. no value o the until: To copy is returned. input to output: puts(gets(s)); s page 110 Programming in C ~Clibrary- Formatted 0 printf(fmt, fmt output: argl, is argl, returns the characters 0 ...) a string ... are that number are specifying format the of output variables to be i static int j = characters to the written standard = sC]1 = "abc" 3; printf ("%5s", s); ==) __abc printf ("-5s", s); ==) abc printf ("-5.2s", =#> ab printf ("%54d", printf ("%-54", printf ("%xd4", If output width 1s s): 1i); ==) 1i); j, i); 37 ==> 37 is too wide for ignored. 37 ==) out output 37; char output format EXAMPLES : short o printf arg2, in page "output width", 111 Programming in C -Clibrary- | page Formatted input:'scanf 0 scanf (fmt, &argl, fmt is -argl, a &arg2 ... string &argn) specifying format to be ... are the variables in that format input scanf returns the number of arguments successfully assigned. Characters are read from the standard input The scan is terminated if the format character does not match the input. Codes for scanf are the same as for printf, except that "hd", "ho", and "hx" read shorts. o Input items are separated by whitespace, which is ignored. The ‘¢’ format is an exception; the requested number of characters are always read including whitespace characters. (only EOF stops the scan) o) EXAMPLES : int i; short 7j; char scanf slC201, ("%d%hd", will scanf &i, &j); produce ("%d%d", will scanf s2L201; &i, cause ("%2d%hd", ("%20c", the scanf j==132 26 j value to overwrite &j); (== 356 &i, i==35, j== in terminal 20 (== characters ("%[abclx%lxyzl", will 132 (== s); next 26 &j); will produce 241 is still scanf i==26, (== produce sl, s2); sl=="bac", 132 adjacent 241 buffer test msgll2s$}I*&” go into (== sl bacyxw s2=="yx" 1 112 Programming I/0 0 in C ~Clibrary- to and from strings: write args sprintf, will o sscanf into a string according to fmt char str [141; static har month L1031 short day = 23; sprintf page (str, produce "%10s str = "November"; %44", == month, "November day); 23" read into érgs from string according to fmt static char str [] = "Hammer 568"; char part [61]1; long number; sscanf (str, "%s%d", part, &number); will produce part == "Hammer", number==568 113 Programming in C -Clibrary- F'ile o) page 114 1/0 A FILE is a structure file descriptor: specifying... 0 STDIN, 1 STDOUT, 2 STDERR, characters left in buffer mode next character in buffer buffer from o stdio.h: #define FILE struct _iobuf FILE pointers: stdin, stdout, stderr file descriptors: 0, fopen - 1, opens a file by name, FILE *fopen (fname, in 2 specified mode mode) EXAMPLE : FILE *fp; fp = fopen ("data.file", mode == "w", open for mode == "w"); seqgential write "r" open for sequential mode == "a" append: o fclose read (fp) Closes a file controlled by fp. open for writing at end Programming in C -Clibrary- File o Character I/0 (continued) 1/0 getc(fp) | putc(c, fp) fgetc(fp) fputc(c, O Line page /% macro */ /* macro */ /% function %/ fp) /* function #/ I/0 fgets(s, n, fp) read at most n-1 chars into s, including newline fputs(s, fp) write o) Formatted to file fmt, fprintf(fp, &argl, ..., &argn) argl, ..., argn) fmt, Block 1/0 fread (buf, size, num, read num items fwrite fp I/0 fscanf(fp, o) s (buf, write fp) of size size, num, fp) num items of size each into buf each from buf 115 Programming /& * * / #include in C -Clibrary- prage Program - to use C standard I/0 to write a containing one 1, two 2s, etc. up to 10 file {(stdio.h> main() { FILE *fptr; char string [101; register i, j; /*Create the file * / if ((fptr = fopen ("FILE.DAT", perror ("OPEN error"), /*Place * the correct write the (i=1 ; i<{(=10 for (3j=0 numbers array to the in "w")) == NULL) exit (0); the array string and file * / for : i++) ; j<i { string if (fwrite ; j++) Lj1 = 1i; (string, perror i, ("WRITE 1, fptr) error"), == exit 3 /%Close * / if the (fclose file (fptr) perror == EOF) ("CLOSE error"), exit 0) (0); (0); 116 Programming in C Error o ~Clibrary- output: perror, page fprintf perror'("file open error'"); write string to stderr -and- write system message to stderr that corresponds to the error code in the external int errno o] fprintf (stderr, write "can’'t open file %s\n", formatted output to stderr fname); 117 Programming in C -Clibrary- System o) an alternative O direct calls (emulated O to to I/0 standard the I/0 (fopen, ULTRIX operating fwrite, system in VMS) creat will create adnew file: returns mode O level page fd = a file creat specifies (name, mode) descriptor (positive UNIX access permissions: owner group read 0400 040 write 04 0200 020 02 execute 0100 010 01 open will open an already integer) others existing file: fd = open (name, mode); returns mode o) a file == 0 == == 1 2 close will descriptor (positive for read, for write, for read/write. close a file: close(fd); integer) ...) 118 Programming in C -Clibrary- System 0 1/0 (continued) read and write: read(fd, read size bytes returns 1f write write size returns buf, size); into buf from fd the number of bytes 0 if end-of-file -1 (fd, buf, size); from buf number 1f read error bytes the -1 0 page to fd of bytes INPUT to written error EXAMPLE: To copy #include <{(stdio.h> OUTPUT main() { char bLBUFSIZI1; short i int fdin, if ((fdin fdout; = open ("INPUT", perror if ((fdout = creat perror while ((i { if = ("open ("OUTPUT", ("creat read 0)) == error"'"), (fdin, (1 ¢ 0) perror('"read 0)) error"), b, -1) exit (1); == -1) exit BUFSIZ)) error"), (1); != exit 0) (1); else if (i != write(fdout, b, i)) perror('"write error"), exit (1); exit 3 (0); | ! 3 From stdio.h: BUFSIZ (512 on most systems) | 119 Programming in C -Clibrary- page 120 lseek o lseek will position within lseek is origin returns o number i offset of bytes for read/write origin); from the origin byte offset 1 byte offset 2 from the beginning, from the current position, byte offset from the the l1seek does offset, open file 0 resulting offset not specifies o (fd, an location from the beginning physically move the byte end. position the for disk arm; the next it I/0 only operation. EXAMPLE: /*function to read randomly a block from a file Ny #include <(stdio.h> int getblock(fd, buf, blkno) int fd; char *buf:; short /*file desc of open filex/ /*address to read intox/ blkno; /*block number to readx/ bytes read { lseek (fd, /*return T blkno or FF'== T > * BUFSIZ, 0): F wvalue: 0 if 0 for end of number file of * / return . ot (read(fd, buf, BUFSIZ) == BUFSIZ); Programming in C ~Clibrary- Heap allocation: o malloc - allocates page malloc, free space on the heap. char *malloc(nbytes) unsigned nbytes; An element of size nbytes 1is allocated, and its address malloc() o is returned. returns NULL pointer on failure. free - frees a previously allocated cell. free(pcell) char *pcell; Free the space pointed to by pcell. Be careful - to free only those malloc’ed! cells previously 121 Programming in C -style- C programming page style Data and variables O o Consistent | and meaningful names Standard defined-types: ushort, tiny, #define ushort unsigned #define tiny char o Manifest constants: EOF; NULL, short 122 Programming in C -style- C programming page stvyle Operators 0 No blank for *p primary plL1l and unary ops: 5.m o) No blank for parens: (x + vy) o) No blank for functions f(x) 0 One blank for binary X o One blank for key words: O Do not assume ops: +y if (...) left-to-right evaluation: a() O Do not + b() assume * c() timing of side-effects within an expression: o) ali++1 = bLj++1; OK ali++1 = bLil; BAD The only guarantees are the sequence full-expr for sequence and guarantees && of | | side-effects C: ’ 7 123 Programming in C -style- C programming Control o Braces above page stvyle: structures and below body { remark("bad value", code): ++nerrs; 3 0 One-tab uniform 0 80-char line o] "else-if" o) - Avoid indents limit: no "wrapped only when necessary; "goto" and "continue" lines" prefer "switch" 124 Programming in C -style- C programming page style: Functions o Layout: #include <{(stdio.h> #include <(stdtyp.h> #include "proj.h" #define TOK short TYPEX varx = NNN; /* comment * / /* describing TYPE func(al, a2, commented func a3) TYPE1l al; TYPEZ a2; /* describe /* describe */ %/ TYPE3 /* describe %/ a3; */ { extern TYPEX varx:; (local declarations> (statements> 3 | o Build and use standard headers (@ Source files functions 0 #includes, 0 No no bigger then 0 Prefer 50 lines; lines then in header rest files; #define, declarations, static “Defensive than nothing but structure than 500 #defines, initializations contain o) no bigger of file they should typedef, and externs. each source to external programming": responsible to avoid Professional code is file out-of bounds references. not allowed to "bomb-out". 125 Programming in C -style- page Common C bugs 1. General Uninitalized wvariables Off-by-one errors. Treating an array as though it were l-origin (instead of 0O-origin). Unclosed comments. | Forgetting semi-colons. Misplaced braces. 2. Types, Operators, and Expressions Using "char" instead of "int" for the returned value from getch. "Backslash" typed as "Slash"; e.qg., ~'/n’ instead of 'O. Declaring function arguments after the function brace, creating spurious local variables. Arithmetic overflow. , Using relational operators on strings; e.g. 5 == strcmp(s, "end" instead Using "=" instead of "==" Multiple side-effects to the in the of "end"). same same memory expression; e.g. sec = ++sec % 60; False assumptions about the time at which post-increment is done. Off-by-one errors in loops with increment. Precedence of bitwise logical operators. (Always parenthesize them.) numbers Right-shifting negative Assuming (Not the equivalent to division). order of evaluation of expressions. Forgetting null-terminator on strings. 126 Common C bugs Control page 127 -style- Programming in C (continued) flow "else" Misplaced Missing "break" in "switch". Loop with first or last case abnormal Loop mistakenly never entered. in some way. Functions and program structure Wrong type of arguments (relying on memory instead of manual). Wrong order of arguments. Omitting static on subfunction’s abiding storage. Assuming that static storage is re-initialized at each re-entry. Macro written without full parenthesization of arguments and result. Pointers and arrays Passing pointer instead of value -- or value instead of pointer. Confusing "char" with "char #". Using pointers for strings without allocating storage for the string. Dangling pointer references -- references to storage no longer used. Confusing single quotes ('\n’) with double quotes ("\n"). Programming in C -labs- MONDAY PROGRAMMING the page 128 ASSIGNMENTS In the following exercises, avoid explanding the scope of exercises so as to involve sophisticated terminal input. For example in exercise 1, avoid generalizing so as sum of numbers up to that input from the terminal. l. Write a program to form the sum of inclusive. Print to the terminal the average of the numbers. 2. Write a program that and prints them back to the numbers sum and the to form from 1 to integer the 25 reads 5 characters from the terminal the terminal in reverse order. 3. Write a program that will read characters from the terminal until newline and print back to the terminal a line of asterisks proportional in length to the binary value of each character typed. Apply a scaling factor, so that the largest ASCII character will still fit program functions as a simple as an analog input signal. 4. Write a program back to the prints letter is typed as that reads 2 terminal the input computer on which you 6. a program which reads Write our and purposes, prints 1s a are numbers larger. to your 5. Write a program which tells bits, i.e. tells how many bits terminal onto an plotter, 80 character treating line. the input This line from the terminal and What happens if a program? the size of exist in an a machine word int on the in running. each word sequence of an on line a of input separate from the line. non-whitespace A word, for characters. Along with each word, print its hash-sum (the sum of the characters in the word), once as a 4-digit hex number and once as a 5-digit octal number. Print the hex number with leading zeroes and the octal number with leading blanks. An empty line of input should produce no output. Programming in C -~ -labs- page 129 TUESDAY PROGRAMMING ASSIGNMENTS In the following exercises, avoid expanding the scope of the exercises so as to involve sophisticated terminal input. J1. Write a function that compares 2 shorts and returns the larger. (passed as arguments) Test the function with a progranm. /2. Write a macro DO which will duplicate the syntax of a FORTRAN DO loop, e.qg. DO i=3,11,2 written as DO(i,3,11,2) meaning a loop from an initial value of i = 3 to a final value = 11 in increments of 2. The variable name, the limits of the loop and the increment are arguments. Test the macro with a program that prints to the terminal the values of the loop during each pass. 3. a. Write a function cmpstr (sl, s2) which returns a true value if strings sl and s2 are equal, a false value otherwise. Compile b. with cmpstr into an object file. Write a program to test cmpstr. cmpstr. Compile it and link it | | 4. Write a macro TOUPPER which will translate a lower case character into upper case using the conditional operator e.g. a ? x : vy Test the macro with a program which reads characters from the terminal and prints back to the terminal the result of the TOUPPER macro on them. 5. The function nfrom (low,high) produces a random number between low and high inclusive. See page 5-24 of the text. Modify nfrom to generate a 1long value rather than a short one. Write a program that calls nfrom 10,000 times to generate random numbers from 1 to 6. Print to the terminal a summary showing how many ls, 2s, etc. were generated. 6. Modify the program calling nfrom in the prior exercise to simulate 10,000 rolls of two six-sided dice. Print a summary showing each possible sum and how many times it occurred. Programming in C ~-labs- page 130 WEDNESDAY PROGRAMMING ASSIGNMENT 1. Write a program that will populate a 50 with the integers 1-50 using pointers, not the array to the terminal on five lines element char array subscripts. Print 2. Write a program that reads your first name and age from the terminal using a single scanf and forms a character string using sprintf with your age at your next 3 birthdays. Print the character string back to the terminal. 3. WHrite the page 7-10 of function the text an appropriate rindex described in Exercise 7-1 on "Learning to Program in C". Test with program. 4. Modify the function to use pointers rather | cmpstr written than subscripts. in a previous exercise Test with a program. 5. Multidimensional arrays will be needed for this exercise. See the appropriate pages of the text and this workbook for assistance. The program tokens.c converts its input into a table of tokens. ©See the supplied listing. A token is defined as a unique number assigned to a word. The first word from the input is assigned to token number 1, the next is assigned to token number 2, etc. When a word is found in the input that is identical to one encountered previously, it is given the same token number previously assigned. After reading all the input, the program prints out the table of token numbers and words. If a word is longer than 8 characters, only the first 8 are stored. - Write consists the functions required by tokens. Your solution of only one source file, with 2 functions: short install char sC1; (s) /*Look for the word s in the table. If found, return its token number. If not found, insert s in the table and return a new token number. If int no space execution S run ABC 1 exit (FAIL);*/ dumptok() /*%Print ocample left, of out the tokens.c: tokens 123 ABC 213 Token table: 1 ABC 2 123 3 12345678 1234567890 token table%/ Programming in C ~labs- page 131 THURSDAY PROGRAMMING ASSIGNMENTS l. Write a program to prompt for and read from the terminal values for part name (maximum chars 10), part number the (6 digits) into 2. and amount a disk file in Write a program that terminal your first the on successive middle 3. name Write name a file lines and stock. using a program created uses an name, using first Obtain and write array middle of pointers name the pointer and array Make 5. Write page last as the 8-5 in 8-7 of that will read the above and print to the program the text program of the text sentence of the gettt.c. to last your records the records read name. last revisions described "Learning runtt to in part report stock of 8-1 each on C". in Exercise Program and print in from Print name, the a in Exercise Program described "Learning exercise to from terminal showing the part name, part number and amount the total amount in stock of all parts. 4. such name. and page 4 structure. 8-2 on in C". Ignore the out the structure Programming in C -labs- page FRIDAY PROGRAMMING ASSIGNMENTS 1. Write a program that reads its 2 arguments from the command line. If the strings are equal, print EQUAL and the string. If the strings are not equal, print NOT EQUAL. If less than or more than 2 arguments are supplied, print an appropriate error message. P 2. Revise the program previously written to create a part number file to create and write to the file using system level 1/0. 3. Write a program that will read the records using system level 1I/0 from the part name file created above and print to the terminal a report showing the part name, part number and amount in stock of each and the total amount in stock of all parts. 132
Home
Privacy and Data
Site structure and layout ©2025 Majenko Technologies