You are on page 1of 172

SIEMENS Technical Academy Licensed vocational school for Industry technologists, electro-technical assistants and technical assistants

of informatics

Ruth Schubert

C - Course
Teacher's book

20.03.99

Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________

1 Content
1 Content.........................................................................................................................................2 2 General considerations regarding C-training.................................................................................7 3 C development.............................................................................................................................8 4 Introduction...................................................................................................................................9 4.1 Basic principle of data processing .........................................................................................9 4.2 What is a program ?...............................................................................................................9 4.3 Program generation with higher programming languages.....................................................10 4.4 The shortest possible C-program..........................................................................................10 4.5 Simple program with in- and output......................................................................................10 4.6 Programs input.....................................................................................................................11 4.6.1 The Editor in the integrated environment of BORLAND-C 3.1........................................11 4.6.1.1 General...................................................................................................................11 4.6.1.2 Block commands.....................................................................................................11 4.6.1.3 Editing commands...................................................................................................12 4.6.1.4 Additional commands .............................................................................................12 4.6.2 About vi.........................................................................................................................12 4.6.2.1 Calling vi.................................................................................................................12 4.6.2.2 The command mode ...............................................................................................12 4.6.2.2.1 Moving in the text..............................................................................................13 4.6.2.2.2 Changing to input mode ...................................................................................13 4.6.2.2.3 Searching in the text.........................................................................................13 4.6.2.2.4 Deletion of text..................................................................................................14 4.6.2.2.5 Copying of text..................................................................................................14 4.6.2.2.6 File insertion.....................................................................................................14 4.6.2.2.7 quit vi................................................................................................................14 4.6.2.3 The input mode.......................................................................................................14 4.7 Pre-processor.......................................................................................................................15 4.7.1 Control of pre-processor function with cc.......................................................................15 4.7.2 Control of pre-processor function with cpp.....................................................................16 4.7.3 Overview of pre-processor instructions..........................................................................16 4.7.4 Symbolic constants .......................................................................................................16 4.7.5 Macros...........................................................................................................................17 4.7.5.1 The pre-processor operator "#"................................................................................18 4.7.5.2 The pre-processor operator "##"..............................................................................18 4.7.5.3 Deleting the definition of a previous #define............................................................19 4.7.6 Insertion of files .............................................................................................................19 4.7.6.1 Standard path for includes in UNIX systems............................................................20 4.7.6.2 Standard path for includes at BORLAND C.............................................................20 4.7.7 Conditioned translation .................................................................................................20 4.7.7.1 Symbol generation for UNIX....................................................................................22 4.7.7.2 Symbol generation for BORLAND-C........................................................................22 4.8 Calling the C-compiler and the binder...................................................................................23 4.8.1 cc (Compiler call)...........................................................................................................23 4.8.2 ld (Binder call)................................................................................................................24 4.8.3 ld call through the C-Compiler........................................................................................25

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
5 C speech elements.....................................................................................................................26 5.1 Identifier...............................................................................................................................26 5.1.1 Reserved names / C-keywords / Keywords....................................................................27 5.2 Data types............................................................................................................................27 5.3 Variables..............................................................................................................................29 5.4 Constants.............................................................................................................................31 5.4.1 Constant routine............................................................................................................32 5.4.2 Boolean constants.........................................................................................................32 5.5 In / Output............................................................................................................................33 5.5.1 Character by character in/output....................................................................................34 5.5.1.1 putchar() output.......................................................................................................34 5.5.1.2 Input with getchar()..................................................................................................35 5.5.2 Formatted in/output........................................................................................................36 5.5.2.1 Output with printf.....................................................................................................36 5.5.2.1.1 Sintactic structure of the printf function call ......................................................36 5.5.2.1.2 Structure of a formatting specification for printf..................................................37 5.5.2.2 Input with scanf.......................................................................................................40 5.5.2.2.1 Syntactic structure of the scanf function call .....................................................41 5.5.2.2.2 Structure of a formatting specification for scanf.................................................41 5.6 Operators and routines.........................................................................................................44 5.6.1 Overview of operators in C.............................................................................................44 5.6.2 C - Specialties................................................................................................................44 5.6.3 Simple assignment operator ..........................................................................................44 5.6.4 Arithmetic operators.......................................................................................................45 5.6.5 Comparison operators...................................................................................................45 5.6.6 Logical operators...........................................................................................................46 5.6.7 Operators for Bit-manipulation.......................................................................................47 5.6.8 Compound assignment operators .................................................................................48 5.6.9 Increment and decrement operators..............................................................................49 5.6.9.1 Prefix quote.............................................................................................................49 5.6.9.2 Postfix quote...........................................................................................................50 5.6.10 sizeof...........................................................................................................................50 5.6.11 Conditioned routines....................................................................................................51 5.6.12 Priority and assessment of operators...........................................................................51 5.6.13 Routines......................................................................................................................52 5.6.14 Side effects in routines ................................................................................................52 5.6.14.1 Rules for avoiding side effects ..............................................................................54 5.7 Control structures.................................................................................................................55 5.7.1 Blocks............................................................................................................................55 5.7.2 if-branching....................................................................................................................55 5.7.2.1 General form of the if-branching..............................................................................55 5.7.2.2 if-instruction without else-branch.............................................................................56 5.7.2.3 Nested if-instructions...............................................................................................56 5.7.2.4 else-if-chains...........................................................................................................57 5.7.2.5 Some common errors when handling if-queries.......................................................58 5.7.3 switch-instruction...........................................................................................................59 5.7.3.1 Basic form of switch-instruction...............................................................................59 5.7.3.2 Variant with partly missing break-instructions..........................................................61 5.7.4 while – loop....................................................................................................................63 5.7.4.1 Standard form of a while-loop..................................................................................64 5.7.4.2 while-loop with empty loop body .............................................................................65

_______________________________________________________ Version IT2.0

.................................................................................................4 Standard functions for string handling .........10.11...........................................................................80 5...............2 Function parameters as value ("call by value").......5 Pointer arithmetics...............4 Sorting of fields with "qsort"...11.............................................10..1 Connection between physical address and pointer arithmetics ....2 The explicit conversion of the data type ...............11...................9 Pointer on pointer .............................................6 for – loop......................................7 Pointer on functions ......2 Strings in assignments to char-pointers.....4 Result transfer through the return value .....85 5.....................81 5..........82 5....................................................................5.............7.......70 5..10..0 .......................................7..............Ruth Schubert C-Course 20............................8 Pointer errors...7 char .......................................................................................................................................11................................................................Instruction...........68 5....10...7................11.............................................................9 goto ..................................91 5...72 5.........10.........86 5.....6...............7.instruction....90 5....8..............................9............7.....................3 The content of a memory cell addressed over a pointer ...........................9....................................68 5...............................85 5......................................................3 Initialization of fields at definition ...................5.........70 5........................8.11.................1 Unidimensional errors ...........69 5............85 5..7...100 5.................................................................10.............................................................................7 break....83 5.................................11.......7.....85 5..........pointer (Strings)....................11........5........................81 5......................................10................................3 Calling the function through the function pointer............................................................................................................................................1 Definition of a pointer field....................1 Definition of a function pointer ...........................10.................................................2 Multidimensional fields ...7..................5 Parameter transfer.......................85 5.............................................................Instruction / Brands........10.....................................................................8............................78 5.................7.....................11......................9.....................................................................89 5...................5 do ..while – loop.91 5....................................................................................................................3 Access..............................10..................71 5...........9..................80 5.......................84 5...........................................10.............................75 5...4 Example of a memory allocation with variables and pointers ........................................2 Function call ..........................65 5....3 Access to an addressed object..................8................94 5..................................................84 5............................................95 5.............................................10......................74 5...........................11.2 The address of a variable .........72 5...........................................84 5................................86 5.............96 5....................................101 _______________________________________________________ Version IT2.............92 5................................................................3 Strings when initializing char-fields................................94 5..................1 Definition of a pointer ..................91 5........6 Argument transfer to the main-function....................12 Memory classes..........................10.....................................................................10............1 Strings as function parameters.11............2 Allocation...............................11 Functions.............................73 5...............................................95 5...............................3 Function parameters as address ("call by reference").....................1 The implicit conversion of the data type ..................................................10 Pointer.................................................87 5......................................................................10..................................2 Assignment of an address to a field element....11...............................90 5..........11...................................11..................................................................7.............................................7............8 continue .....77 5.............................................2 Assigning a function's address ..............9 Complex definitions.......83 5.........10..................03.........................7............................76 5.............................................10.....................................1 Type test of parameters under UNIX................11..........................................3 Function declaration.......99 _______________________________________________________ 5.......................................10...........98 5.......9.......6 Pointers and fields ...............................................9...................................1 Definition...........................................................................7......76 5.10.......8....................................................8 Data type conversions...............1 Function definition..................................................11.....................76 5................9 Fields (Arrays).............................8 Recursive function call ...............................................................................10.........................................66 5..........

..............12..132 5......17..........................................3 Linked lists......................................................................................3..4 Resetting characters ...........132 5..............................................................136 _______________________________________________________ Version IT2.......................................................operator....................5 Definition of a structure field.......................................................17...133 5...........................17............................................2 Formatted writing .1 Reading block by block........................................................................14.......17.............136 5....................2...................................................18.......116 5...........130 5..................17..2 malloc.........................................2 Write string......3 Definition of a structure and simultaneous declaration of the structure type ...14.........130 5..........17.........135 5...........................136 5............................................107 5.14.........................13.............................................................128 5....2 The '->' ...............2 Declaration of s structure type...........................5 fflush – empties the buffer ........................1 Note for examples when using BORLAND-C 3.........................................................................3 The macros getchar / putchar...17..................17.............................................................124 5..........7...........14...110 5.......................................18.................................................1 Formatted reading....................................................2 fopen – opens a file...............................................104 5............................129 5..................1 calloc..............4 free.................................................................120 5............................99 _______________________________________________________ 5....103 5..............................12.............103 5..........................................17..6.......2 Writing block by block..........14.......................2 Character by character writing ............................................4 Data type indentifier const..118 5.....................17..........................11 feof – Detecting the file end ........................9.......9 Reading and writing block by block .......17......114 5...........3....113 5........................................................................... which can be filed in the data range ..7....................17 File accesses through the FILE-structure.........118 5........123 5.111 5..............................................17..17.........17....................................................119 5.....................................................131 5........1 Variable of the auto memory class.....................................14 Simple structures............................................8....................14........................7 Reading and writing strings.............operator.....................3 realloc.....................................0 .................................................17...................112 5...........................................................3 Variables.....................8 Formatted reading and writing .......................102 5...........................12.............17.........................17.....................................1 The '.................4.....13......................................................................4 fclose – closes a file .....................108 5.................122 5.....................................................2 static-variables..........123 5....................................................................................................................18 Optimized organisation of same type structures..........................1 Global variables and the external-declaration.................107 5..111 5........................................................................9..' ............................14...........17...............................................17...6 Character by character reading and writing ............................3 rewind – Resetting the write / read pointer.....................2 ftell – Indicating the position of the write / read pointer........18.......................................................................................4........6...................................................121 5............................................113 5.................4 Accessing structure elements.......................6 Initialization of structures .............................13..12......17.........Ruth Schubert C-Course 20....1 Reading strings........1 fseek – Positioning of the write / read pointer.17...............112 5..................................10.................127 5.....134 5..................17.....6.......................................10 Functions for random file accessing ...................17................111 5.1 Particularity when indicating the file name in case of BORLAND-C..........................................16 enum.............................................101 5.....................8.........................................125 5..6.12.........................................................13....2 Variable of the memory class register..1.....2 Definition of a recursive structure.............................1 List of FILE file access functions (incomplete).........................................................................................................................................................................................128 5.......10................................................10........03.....134 5........12....................113 5........................................15 typedef....................................14................................................127 5..................................................109 5................................128 5.............................13 Dynamic memory management ...............122 5...............1 Definition of a structure...............1 Character by character reading .......117 5...109 5....................17........................................................

..................................................................03.......................................................171 6......................................................2 toupper..............................................................................19 Bit fields.......................2 srand.............................18..................................8 strlen....................................167 6...................................................168 6.....1................161 6...........................................................................................................167 6....................144 5...............................................................1 atoi...........169 6......................................................1.....................4 Binary trees...18........................................................................................................................4 Ring link...................7 strncpy.........162 6.....1 Simple forward linked list ..........................9 strtok.......1..............................................................................................0 ............................................3............................3................18........2.......................................137 5................................157 5..................21 Unions (Variants)................170 6..............................................................................................................................169 6.........................3 atof.....................................................2.........................4 Macros for character conversion.......20 Bit masks..160 6.....................................6 Program ending.......................................................4 strcmp.................163 6...................................1...............................................5 Random numbers generator...............................1........................3..........................139 5.........................................................1...................................99 _______________________________________________________ 5................148 5......................2 strncat...........................................................................................................................18.........................................1 String processing.................166 6...........................1..............................................................................................2 Converting character strings to numbers .......................................................................................................................................................................................................162 6..........................................2...................................................160 6................................3 Double linked list ..................................2.......1 strcat........................1...................156 5..............................................................................................151 5..........................................157 6 Some C-library functions..........................................163 6.......................18....................172 _______________________________________________________ Version IT2................................................141 5..............................2 Simple backwards linked list ..................................................5 Hashing............1 rand............................................................................................165 6..............................................................................................3..................................170 6......2 atol....................................170 6...............1 tolower................................164 6............................................................3 Macros for verifying character features .................................5 strncmp.............6 strcpy...........................................................................165 6...............................18............................Ruth Schubert C-Course 20..............4...4.......................5..........3 strchr................................................................163 6........5.................160 6.......................................4 sscanf..................................................................................................................1.......161 6..............

99 _______________________________________________________ 2 General considerations regarding C-training The work documentation for the C-training is not suitable for individual study. The lines marked with a bar on the left page margin must be filled in with information obtained during the course. Furthermore.Ruth Schubert C-Course 20. which in some cases must contain the description of the functional interfaces · comments for the important program steps (however. While performing the exercises. several C-instructions were partly written in a line. To make the examples of this script more clear. well structured and clear program structure · the function descriptions. you must pay attention to: · correct functioning of the program · accurate fulfillment of the task · simple. not each command must be described) · a comfortable user interface The following is valid in principle: better program in a simple and clear way than making it complicated.03. error handlings were mostly dropped in the program parts.0 . You should avoid both in your program! _______________________________________________________ Version IT2.

Ruth Schubert C-Course 20. The upgrade of the programming language C to C++ (a language. The standardization drafts published in 1988 were extensively used in this document. C became more important for application programming. C-programs' portability can however be guaranteed only by standards compliance. which is explained by the portability of the programs. _______________________________________________________ Version IT2. Thereby the language was renamed C. UNIX was written in C and implemented in a PDP-11.7. in the Bell Laboratories of Murray Hill. compiler). C was used a few years only for system programming (operating systems. which fulfills the requirements of object oriented programming) is not covered in this framework. to implement the UNIX operating system on a PDP.03. In 1972 Dennis Ritchie adapted this programming language and enhanced it with the type concept (see "Data types" on page 31). Since 1983 there is an ANSI board (American National Standard Institute) working on C standardization.99 _______________________________________________________ 3 C development The B programming language was developed in 1970 by Ken Thompson.0 . C should be seen as a subset of C++.

· Processing: The data read in during the input is processed and output data is generated.99 _______________________________________________________ 4 Introduction 4. The task of the programmer is to issue such a "cooking recipe". because no other traffic light shows "green" at the moment. F example E A program should calculate a square root: · Input: user introduces a number over the keyboard.2 What is a program ? A program is a "cooking recipe" for a computer to perform a certain task (for example square root calculation or traffic light control) input.1 Basic principle of data processing All programs (written in any programming language) work by the same basic principle: · Input: certain data is introduced in the program or the program acquires this input data itself. 4. · Output: the program switches the traffic light to "green". that the traffic light for this car can be switched to "green". _______________________________________________________ Version IT2. · Processing: square root is calculated.0 . processing and output.03. · Output: the square root is written by the program on the screen.Ruth Schubert C-Course 20. F example E A program controls a traffic light: · Input: a car drives on a contact loop. · Processing: the program determines. · Output: The output data is issued under a certain form.

3 Program generation with higher programming languages Because the computers themselves only understand a very primitive "language".5 Simple program with in.h> void main(void) { int number. An instruction in a higher programming language is converted by compiler (a translation program) in many instructions into machine code. In this case. which is always called main. there are no instructions in the accolades.Ruth Schubert C-Course 20. there were higher programming languages developed.and output /* This program calculates the square of a number to be entered and displays the result on the screen: */ #include <stdio. /* processing */ printf("%d\n". when it is ended (thus the void at the beginning of the line). _______________________________________________________ Version IT2. number).4 The shortest possible C-program void main(void) {} Each C-program must have a main program. /* buffer for number */ scanf("%d". &number). 4. /* input */ number = number * number. this main program receives no parameters when it is started (thus void in the round brackets) and it returns nothing to the operating system. which are easier to understand by humans and are more readable than machine code. 4.03. Furthermore. /* output */ } • scanf: Function from the standard library for the formatted input of standard input (see "Input with scanf" on page 45).0 .99 _______________________________________________________ 4. which could perform the program. named machine code.

The active editor window is closed with Window¦Close.1 General There are several methods to activate an open editor window: · Clicking • press Alt-# (where # is the number of the editor window) · select the window of the Window¦List dialogue window • press or click F6. Press F10. "Output with printf" on page 40).6.:each C-instruction is finished by a semicolon. 4. Before the text can be cut. 4.6.03.1.6. where the open windows are activated one after another. a block must be marked first.Ruth Schubert C-Course 20.1 4. to quit the editor.2 Block commands Function Set block start Set block end Copy marked block at cursor position Shift marked text at cursor position Copy block through clipboard: Key pressing Strg+K B Strg+K K Strg+K C Strg+K V Strg+Einf Umsch+Einf (at the insertion location) _______________________________________________________ Version IT2. · Text between /* and */: is interpreted by the compiler as a comment and ignored.1.6 Programs input 4. · \n: Special character for the output of a new line to the standard output · .99 _______________________________________________________ • printf: Function from the standard library for the formatted output on standard output (s.0 .1 The Editor in the integrated environment of BORLAND-C 3. copied and then inserted again.

which must be however entered blind and almost never be confirmed with RETURN.1.1.6.Ruth Schubert C-Course 20. the user can enter commands like Search or Text Replacement.6. the cursor can be moved using the cursor keys. · The user can enter text in the input mode. The following commands are possible.1 Calling vi vi <filename> 4.2 The command mode After calling the vi. In the command mode. _______________________________________________________ Version IT2.6.4 Additional commands Function Show last compilation error Show next compilation error Help Help index Full screen Undo Switch to user display Key pressing Alt+F7 Alt+F8 F1 Umsch+F1 F5 Alt+Backspace ALT+F5 4. you are in the command mode.99 _______________________________________________________ Delete block Strg+Entf 4.2.2.6.03.0 .6. 4.3 Editing commands Function Key pressing Del Delete character Backspace Delete character left Strg+Y Delete line Ins Insert ON/OFF 4.2 About vi For vi there is a strict delimitation between input mode and command mode: · Im the command mode.

6.3 Searching in the text /<text> Search from Cursor forwards to <text>.1 Moving in the text These commands serve for shifting the cursor mark within the text: 0 $ ^ w b H M L <n>G G Set cursor at the beginning of the line Set cursor at the end of the line Set cursor at the text start of the current line Shift cursor forward by one word Shift cursor back by one word Set cursor on the first position of the first screen line Set cursor on the first position of the middle screen line Set cursor on the first position of the last screen line Set cursor on the first position of the n-th file line Set cursor on the first position of the last file line 4.Ruth Schubert C-Course 20. This command must be quitted with RETURN!! n Repeat the last search action % Search for the next matching bracket (nesting is considered) _______________________________________________________ Version IT2.6. it can be finally repeated by entering a point.2.2.6.99 _______________________________________________________ When a command was entered. 4.0 .2.2.2.2. This command must be quitted with RETURN!! ?<text> Search from Cursor backwards to <text>.2 Changing to input mode The following commands are used to change to the input mode (see "The Input mode" on page 18): i I a A o O Insert before cursor position Insert starting with current line start Append after cursor position Append at line end Insert new line under the cursor position and set cursor on the beginning of it Set new line Insert new line through the cursor position at its beginning 4.03.

99 _______________________________________________________ 4.6. in which the cursor is placed D Deletion of character. Store current file Store current file as <filename> 4. where the cursor is located.6. If the vi was started without indicating a file name.2.2.Ruth Schubert C-Course 20.5 Copying of text <n>yy Copies the rest of the line.03.0 .6 File insertion :r <filename> :w :w <filename> Inserts the file content <filename> in the place. where the cursor is placed and the next <n> .2.1 lines in a buffer p Inserts the buffer content where the cursor is placed 4. where the cursor is placed – the next line is appended to the end of the line.2. where the cursor is placed <n> dd Deletion of n lines starting from the line. then a file can be loaded using this command. 4.2. where the cursor is placed (the deleted text is stored in a buffer) J Removes the line break of the line. where the cursor is placed.7 quit vi :wq or ZZ :q! Storage of current file and quitting vi quitting vi without storing anything 4.6.6.3 The input mode There are no correction possibilities in the input mode: <BACKSPACE> Deletion of a character left of the cursor _______________________________________________________ Version IT2.4 Deletion of text x Deletion of character.2.2.2.6. upon which the cursor is placed dw Deletion of word. upon which the cursor is placed and of all further characters until the end of line dd Deletion of line.2.

where the cursor is placed.7 Pre-processor By calling the C-compiler. 4.99 _______________________________________________________ <CTRL>U Deletion of line. Pre-processor instructions are finalized through the line end. The result file contains no other lines which start with #. the cursor keys cannot be used during the input mode! 4.1 Control of pre-processor function with cc If only the result of the pre-processor instructions should be controlled. Through ESC one can change from input mode to command mode. The pre-processor instructions have been performed. Example  cc ueb.7.03. a process capable program is generated in several steps from the source program: · perform pre-processor instructions · translate into machine code (in some systems under certain circumstances through the assembler) · Bind.Ruth Schubert C-Course 20. as opposed to the C-instruction lines. in case of macro definitions). should be finalized with the \-character (cancellation of Return). which should have a following line. which must be the first visible character (not empty character or tab) of the line.c -P Result can be found in ueb. automatic call of binder All pre-processor instructions are marked by the character #. then the lines. then the compiler must be called using the -P switch (see "Calling the CCompiler and the Binder" on page 27).0 . If a line is not sufficient (ex. Attention M In some systems.i _______________________________________________________ Version IT2.

Example  cpp ueb.0 . for the respective file. because the constant is defined at a central location.4 Symbolic constants The use of symbolic constants has the following advantages: · Programs are easier to modify.03.3 Overview of pre-processor instructions #define #undef #include #if #ifdef #ifndef #else #endif symbolic constants (see page 19) and macros (see page 20) Deletes the definition of a previous #define (see page 22) Insertion of files (see page 23) Conditioned translation (see page 24) 4.7.2 Control of pre-processor function with cpp If only the result of the preprocessor instructions should be controlled. The pre-processor replaces in the program all NUMBER symbols with the value 100. · Programs can be read more easy The names of symbolic constants should always be written in capital letters.i.Ruth Schubert C-Course 20. a modification of constants concerns only one program line .7. 4. the symbolic constant NUMBER is defined. _______________________________________________________ Version IT2.c Result can be found in ueb.99 _______________________________________________________ 4. then CPP must be called by DOS-Prompt from the pre-processor.7. Example  Using the #define NUMBER 100 Instruction.

c+d).03. A text (ex.7. then the pre-processor introduces the agreed text there.0 . apart from that. c+d).5 Macros Macros can also be defined using the #define instruction.y) x * x + y * y Call: erg = SQ(a+b. Is expanded to: erg = a+b*a+b+c+d*c+d.  ttention  A The macro parameters should always be included in round brackets in the macro definitions.99 _______________________________________________________ 4.b) ((a)<(b)?(b):(a)) Call: var_max = MAX(var1.y) ((x) * (x) + (y) * (y)) Call: erg = SQ(a+b. NL. Is expanded to: erg = ((a+b) * (a+b) + (c+d) * (c+d)). Macro parameters can be agreed. One or several Cinstructions can be resumed under a macro name.Ruth Schubert C-Course 20. The macro mechanism is a simple text replacement. Example  #define MAX(a.instruction. NL. _______________________________________________________ Version IT2. Example  /* Sum of squares: */ #define SQ(x. C instructions) receives a name through the #define . Example  #define NL printf("\n") Call: printf("hello"). round brackets should comprise the entire macro definition! Here the above example when breaking this rule: /* Sum of squares: */ #define SQ(x.var2). printf("how are you"). If this name is called somewhere in the program.

for example. Is expanded to: erg = ((a++) * (a++)). /* ATTENTION: 'a' is increased twice !!! */ 4.a) Call: int var1 = 4.99 _______________________________________________________ Attention  The current parameters should never receive assignation operators at macro call. Example  /* Square: */ #define Q(x) ((x) * (x)) Call: erg = Q(a++).7.p2) printf("PR1: %d\n". var##p1) Call: int var1 = 100.Ruth Schubert C-Course 20.5. p1##p2) #define PR2(p1) printf("PR2: %d\n". PR1(var. the a++ phrase should never be the current parameter of a macro. #a . _______________________________________________________ Version IT2.0 . Example  #define PR_d(a) printf("%s = %d \n".5. Output: Result: var_1 = 4 4. Example  #define PR1(p1.1).7.2 The pre-processor operator "##" The pre-processor operator ## triggers the connection of the string (mostly assigner of macro operators) to other operators.1 The pre-processor operator "#" The pre-processor operator # triggers. PR_d(var_1).03. that a macro operator is used as string for the macro expansion. printf("Result: ").

when macros should be used in different contexts.7.6 Insertion of files Example  #include " constant.Ruth Schubert C-Course 20.7. _______________________________________________________ Version IT2.0 .h" The pre-processor replaces the #include-instruction through the content of the constant. This is especially useful.h file. however.03. in case of rules they should contain no executable code. ERROR #undef EXPAND "" /* empty text at the end of the table */ }. Example  #define ERROR \ EXPAND(EVERYTHING_OK.text) code.5."Everything o."Parameters are wrong !") \ EXPAND(PARAM_TOO_LARGE. Include files can have random content.k. !")\ EXPAND(PARAM_WRONG. 4.3 Deleting the definition of a previous #define A previously made macro definition or symbolic constant can be reversed again with #undef."Parameters are too large !") /* Generate an enum with the error codes: */ enum { #define EXPAND(code. ERROR #undef EXPAND NUMBER_OF_ERRORS } error codes.99 _______________________________________________________ PR2(1). text) text. Output: PR1: 100 PR2: 100 4. /* Generate a field with belonging error texts: */ char *error text[] = { #define EXPAND(code.

h" Includes. but they are not also translated).6.03.h> 4.1 Standard path for includes in UNIX systems In UNIX systems the standard folder for includes is for example the /usr/include folder 4.Ruth Schubert C-Course 20. _______________________________________________________ Version IT2. the standard include path is determined in the normal DOS path (through PATH-instruction). temporarily "delete" program parts (the program parts remain in the program.0 . Example: #include <stdio. 4. Example  #include "beispiel.7.7.7 Conditioned translation #if #ifdef #ifndef #else #endif The conditioned translation is needed to: • store different program variants (for example for different HW-environments) in a program.99 _______________________________________________________ Normally they contain:  efinitions of symbolic constants D Macro definitions (see "Macros" on page 20) • extern-declarations (see "Global variables and the externdeclaration" on page 113) Structure type agreements (see "Simple structures" on page 122) or typedef-instructions (see "typedef" on page 128) The names of include files usually end with ". then the file name must be included in the double high comma.6.7. which lie in the standard include folder of the compiler.2 Standard path for includes at BORLAND C For BORLAND C. must be closed through pointed brackets.h" Should include files be searched by the pre-processor in the current file folder or at a certain path name (personal includes).

query. Example  #if (defined SYM1) && (defined SYM2) && (SYM3 > 10) Successful test  What does the following program display? File: ueb. #else int var_1 = 2. var_3 ) } _______________________________________________________ Version IT2. var_2. if FILE is defined.99 _______________________________________________________ install "switchable" test outputs into the program.h" void main(void) { #ifdef VARI_1 int var_1 = 1. float var_3 = 3. float var_3 = 4.. #endif Preprocessor operator defined Using the defined pre-processor operator.03. char var_2 = 'a'.4.Ruth Schubert C-Course 20. Program variants can be generated using the #else-instruction. #endif In this example the program line is deleted with the printf by the preprocessor. if the DEBUG symbol is missing."hello world\n").0 .c #include "ueb. Example  The following program fragment displays a text in a outfile file. otherwise it shows it on the screen: #ifdef FILE fprintf(outfile. the existence of several symbols can be verified with a single #if. this means it is not also translated. char var_2 = 'b'. #else printf("hello world\n"). countmax).5..   Example  . #ifdef DEBUG printf ("Test output: countmax = %d\n". #endif PR_icf(var_1.

p2. c) PR1(p3.2 Symbol generation for BORLAND-C A symbol which can be tested with the #ifdef. f) Hot tip  In standard-C. Result: var_1: 1 var_2: a var_3: 3.03.0 . format) \ printf("%s: %"#format "\n". var).400000 4.or #ifndef-instruction is generated either by a #define-instruction or by the –D switch in compiler call (see "Calling the C-compiler and the binder" on page 27).7. triggers the same result as: char *p = "hello here I am". Example  cc ueb. For example char *p = "hello " "here " "I am".7.7.7.1 Symbol generation for UNIX A symbol which can be tested with the #ifdef.99 _______________________________________________________ File: ueb.or #ifndef-instruction. #define PR_icf(p1.c -DDEBUG for compiler call corresponds to: #define DEBUG in the program 4. d) PR1(p2. #var. is generated either by a #define-instruction or by an entry as Defines in the IDE of the BORLAND-compiler _______________________________________________________ Version IT2.Ruth Schubert C-Course 20.h #define VARI_1 #define PR1(var. p3) \ PR1(p1. a string can also be indicated in several part strings.

The following steps are made for the compilation: 1.a (library) cc performs automatically only the necessary translation steps respectively only calls the binder.i _______________________________________________________ Version IT2.c prog. The most important switches Switches Meaning -c cc only performs the first three steps and generates object modules -S cc only performs the first two steps and generates assembler sources -P cc only performs the first step.s cc -P prog.c Output files prog1.0 .03. The data transferred to cc can be: • .s (assembler source) • . 4. Bind to an executable program (see "ld (binder call" on page 28). Translate in assembler code.o (object file) • . also the binder for the program in the <filename> file.c (C-source) • . only the pre-processor instructions are replaced. 3. Carry out pre-processor instructions 2. This Example cc -c prog1.8 Calling the C-compiler and the binder 4.8.Ruth Schubert C-Course 20. implicitly.99 _______________________________________________________ 4.o cc -S prog.o prog2.c prog2.1 cc (Compiler call) Call cc [-<schalter>] <dateiname> Description Calls the compiler and. Assemble in object code.c prog.

] Description ld binds the files in the indicated sequence. This function then calls main(). object modules from indicated libraries are bound. the correctness of the pre-processor instructions can be verified. ld can only satisfy forward references. this means that the sequence of the modules in the link list is important ! To generate a run-capable program. If this switch is dropped. the first module of the link list must be the runtime start function /lib/crt0..0 . then the program name is a.. [-l<libname>.Ruth Schubert C-Course 20. The process capable program is filed as <prgname>. The most important switches Switch Meaning -s ld removes the symbol table (hinders test) _______________________________________________________ Version IT2. In addition..03.2 ld (Binder call) Call ld [-<switch>] <file>. if an external reference is open on them.8.c -o prog prog D<name> or D<name> = <value> cc prog..c -o prog prog 4.out Corresponds to a pre-processor instruction in the programm: #define <name> or #define <name> <value> -o <prgname> cc prog.99 _______________________________________________________ way.o.

Ruth Schubert C-Course 20.a or /usr/lib/lib<libname>. Output file is <filename>.a for resolution of external references.a (if the first one does not exist at /lib) for resolution of external references No local symbols are recorded in the symbol table of the output file local symbols are recorded for test purposes Separation of text.8. which are indicated when calling cc. then the translated modules and the Cstandard library libc. The run-capable program is filed in prog. the -x switch is valid (no local symbols).out -x -X -n -o<filename > Example  ld /lib/crt0.a and the C-Library for float arithmetics /lib/libffp. ld switches.o -lc -lffp -o prog ld binds the runtime start function with progl and prog2 and offers the C standard library /lib/libc.o prog2.o progl. 4.3 ld call through the C-Compiler cc calls ld so that first lib/crt0. _______________________________________________________ Version IT2.a are bound.03.and data segment. are transferred directly to ld.o.99 _______________________________________________________ -l<libname> ld searches the libraries /lib/lib<libname>.0 . The text segment is then write-protected and cannot be overwritten by a program error. not a. In addition.

_______________________________________________________ Version IT2. because this can lead to name misunderstandings in many C compilers. exception: underscore · they must start with a letter.Ruth Schubert C-Course 20.1 Identifier For the name or definition of · Constants (see page 35) · Variables (see page 33) · Functions (see page 94) Identifiers (names. if an identifier gives an indication about the object's function. they should not start with underscore.0 .99 _______________________________________________________ 5 C speech elements 5. identifier) are necessary.and small letters are differentiated · Names for variables or functions are usually written as small letters · Names for constants are usually written as capital letters · Identifiers are not allowed to be C-keywords · Keywords are always written with small letter · local identifiers may consist of maximum 31 significant characters. The following rules are valid for these identifiers: · they may not contain special characters. Program readability is essentially improved.03. · they may consist of capital or small letters · Capital. · The identifier selection should be made carefully.

. function or constant must get a certain data type assigned.0 ..1 Reserved names / C-keywords / Keywords auto break case const continue default double else enum float for goto int long register short signed sizeof struct switch typedef unsigned void volatile char do extern if return static union while Successful test  Mark the wrong and not clearly identifiable identifiers ! Identifier.is wrong abc 2_count _begin float multiplication_table Mark100 hundred_thousand_dollar_counter count*2 MINIMAX _1_counter hundred_thousand_marks_counter Wrglgrmpf if_then_else 5.Ruth Schubert C-Course 20... .99 _______________________________________________________ 5.03..1. .2 Data types Each variable.ist correct _______________________________________________________ Version IT2..

03.Ruth Schubert C-Course 20. _______________________________________________________ Version IT2.0 .99 _______________________________________________________ The basic data types of C are: Characters: char unsigned char signed char Integers: int short long unsigned Floating point numbers: float double long double The representation of individual data type in the memory and thus the numerical range depend on the computer type or the compiler.

1 x 10+4932 The numerical ranges of the individual data types are determined in the Standard-C in the Includes float.0 when using it as 16-Bit compiler: Data type Length in bits Allowed numerical range unsigned char char enum unsigned int short int int unsigned long long float double long double near (pointer) far (pointer) 8 bits 8 bits 16 bits 16 bits 16 bits 16 bits 32 bits 32 bits 32 bits 64 bits 80 bits 16 bits 32 bits 0 to 255 -128 to 127 -32768 to 32767 0 to 65535 -32768 to 32767 -32768 to 32767 0 to 4294967295 -2147483648 to 2147483647 3. This feature's description follows later. Definition of variables within the validity range of a program and the validity duration is determined.h.03. when defining the variables.Ruth Schubert C-Course 20.4 x 10-4932 to 1.4 x 10+38 1. When defining a variable there is memory space reserved This memory space gets a symbolic name allocated (variable name).0 .3 Variables Definition of a variable: <type> <name>.7 x 10-308 to 1. Example  _______________________________________________________ Version IT2.7 x 10+308 3.4 x 10-38 to 3.99 _______________________________________________________ Here as an example the valid data types for the BORLAND C++ compiler 5. Apart from that.h and limits. 5. The size of the reserved memory space depends on the data type of the variables. the validity range within a program and the validity duration is determined.

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
int number_1; char zeich;

unsigned marker; double auxiliary counter; Several variables of the same type can be defined in a list. Example  int number_1, count, marker; char in_char, out_char; Variables can be initialized when defined. Example  int sum = 0 , first = 100; char response = 'n';

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________

5.4 Constants Type Int / short Representation decimal octal hexadecimal long decimal hexadecimal float / double4 Example 123 -3 32000 03331 011 0xA0012 0x123F 2345L3 40000L 0x1ffffL 0xlL 3.1415 12.74e-7 -135.76E3 +17E-2 .012e3 'x' 'B' '*' '\n' (newline) '\t' (tab) '\f' (formfeed) '\\' (backslash) '\'' (single quote) '\ddd' (Bit sample in octal representation) '\0' (Bit sample = 0 è String end character)

char

1 If 2 If

the first number of an integer number constant is 0, then this constant is an octal number. an integer number constant starts with a 0x or 0X, then it is interpreted as a hexadecimal number. 3 A l respectively L behind an integer number constant marks a constant as long value. 4 Floating point constants are always shown with double exactness

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________

Example 
· Deleting the display and then "hello" output: printf ("\033[2J hello \n\n"); /* For DOS-systems */ printf ("\033[14J hello \n\n"); /* For UNIX-systems */ Example  · Assigning the ASCII-codes for 'ESC' to a char-variable: char cvar; cvar = '\033'; or cvar = 0xlB; or cvar = 20+7;... 5.4.1 Constant routine A routine which consists only of constant values and operators is already assessed by the compiler (not at runtime). A constant routine can be implemented anywhere there can be constants as well. Example  #define MIN 100 #define MAX 1000 .... int middle; middle = (MAX - MIN ) / 2; /* Assignment of a constant expression */ 5.4.2 Boolean constants There is no boolean data type in C; this means variables which can only show the TRUE or FALSE values. These logical values are realized in C as integer constants. Thus the following is valid:

_______________________________________________________ Version IT2.0

026 0x123 0..03. if (comparison).5 In / Output The C language range contains no commands for in/output... Successful test  To which data types do the following constants belong? Please also indicate the number representation of the constants if necessary! Constant. comparison = a < b..is of the data type: 5.Ruth Schubert C-Course 20. int b = 2.. 2346 15.99 _______________________________________________________ • 0 corresponds to FALSE • unequal 0 corresponds to TRUE Example  int comparison. which make the in/output functions and other functions available. To use most of the I/O-functions it is necessary to draw in a standard _______________________________________________________ Version IT2. This is why each Ccompiler has libraries with its delivery.0 .. int a = 1..27E10 2L 'x' 0473 0xABCDL 66899 .

_______________________________________________________ Version IT2. char = 0x31. The return value of putchar is the issued character or EOF.0 .h> 5. putchar(char). putchar('\6l') putchar('\007').h include! 5.1. They are defined in stdio. When calling these two macros it is essential to include the stdio.1 putchar() output putchar gives a character output of the type int on standard output: int putchar (int character).03.1 Character by character in/output For a character by character in/output the two macros putchar and getchar are available in C. This happens through the following pre-processor instructions at the beginning of the program: #include <stdio.5.Ruth Schubert C-Course 20. putchar(1).99 _______________________________________________________ include into the C-program. putchar(char). Example  int char = 'a'.5.h. /* Output of 'char' */ /* Output of '1': */ /* Output of '1' */ /* Output of '1' */ /* Output of octal number 7 corresponds to the ASCII character for alert characters (Beep) */ /* Lead character output for new line */ putchar('\n').

Each character of the line and the lead character for [Ret] must then be read with a getchar()-call each out of the keyboard buffer.. where xxx are the digits of the octal number \n New line \f New page \t Tab \b Backspace \' Simple apostrophe \\ Backslash 5.03. Example  /* the user needs to give 2 responses */ #include <stdio.. /* Delete keyboard buffer */ if (response == 'j') _______________________________________________________ Version IT2. if the line is closed by [Ret]..99 _______________________________________________________ List of special character constants \0 ZERO (binary zero 0x00)..Ruth Schubert C-Course 20.1. printf("Do you want to delete? [y/n]: "). . response = getchar(). The return value of getchar is of int type. The content of an input line can only be read out with getchar(). while (getchar() != '\n').2 Input with getchar() getchar reads a character of standard input..h> main() { int response..0 .5. int getchar(void). string end character \x Octal number. The read-in character is the return value of getchar..

.. a. arga...5. The values formatted like that are included into a freely defined text string and displayed upon standard output.0 .Ruth Schubert C-Course 20.. printf("This is a test: ").2.5..1 Output with printf The standard function printf enables the conversion of numeric values into character representations.. /* Delete keyboard buffer */ . b = A 5.1 Sintactic structure of the printf function call printf("Lead character string". while (getchar() != '\n'). Display output: This is a test: Variable a = 99..99 _______________________________________________________ { printf("Do you really want to delete ??? [y/n]: "): response = getchar(). in case of error.5.. printf("Variable a = %d. Example  int a = 99. b = %c ". } } 5.. argb. The return value of printf is the number of displayed characters or a negative number.1. char b = 'A'.2..03. printf is also frequently used only for mere text output.).2 Formatted in/output 5. b). _______________________________________________________ Version IT2.. The control character string contains · text to be displayed · Formatting specifications for the values to be displayed · Lead characters (special character constants).

2 Structure of a formatting specification for printf A formatting specification consists of several format elements. according to the formatting specification and set on the position in the output text. as described at putchar() under "List of special character constants" (see page 39). The type of transferred arguments must fit the formatting specifications.5. This value is converted to printable characters.2.0 .03. a value must be transferred as an argument (argn) to printf. The f and e formats require the transfer of a floating point number! 5.99 _______________________________________________________ For each format element indicated in the control character string. The general format of a formatting specification is the following: %<Alignment><Minimum width>. where the format element in the control character string is located. The control character string may also contain lead characters.1.<Width behind point>l<Conversion characters>5 _______________________________________________________ Version IT2.Ruth Schubert C-Course 20.

filled with zeros on the right positive numbers preceded by '+' Right aligned.03. with leading zeros Left aligned. <Alignment> % Marker for the beginning of a formatting specification The value is displayed leftaligned. then the output field becomes accordingly wider. must only be here. <Width after point> . If the value output indicates more positions than <Minimum width>. one. Number which indicates how many digits should appear for the floating point number on 0 -0 + No indication <Minimum width> One or several digit decimal number .or several digit decimal number _______________________________________________________ Version IT2.Ruth Schubert C-Course 20. if <Width after point> follows. The following table indicates what the meaning of each format element is: Format element Allowed value Meaning % . Rest empty characters Number which determines a minimum field width for the value output. The output field widths are thus variable. printf then takes the corresponding value out of the argument list. This is used to indicate a value column suitable. the output field on the right is filled with empty characters Right aligned. Separator.0 .99 _______________________________________________________ 5 For <minimum width> and <width behind a decimal point> a '*' can be indicated.

0 . it is displayed in scientific notation (example -1. The string is displayed until the text end character ('\0') or until the length. it is displayed in decimal writing (for example 123. The argument is displayed decimal The argument is displayed octal The argument is displayed hexadecimal The argument must be a float-number. The standard for floating point numbers is 6 after-comma positions.03. The character 'l' indicates. which is determined by <Width l The letter 'l' d o x f e c s _______________________________________________________ Version IT2.Ruth Schubert C-Course 20.456789). The argument must be a float-number. that the belonging argument (the value to be displayed) is of long int type or double.99 _______________________________________________________ the right of the decimal point or how many characters can be maximum displayed by a character string. The same is valid for the number of decimal positions. If no indication exists on the position of this format element. then the default value of 6 decimal positions is valid. as for the conversion characters The argument is displayed as individual character The argument is interpreted as a pointer on a character string.234567e+02).

printf("dez: %d okt: %o hex: %x char: %c"."Column2").Ruth Schubert C-Course 20. which indicate according arguments.2 Input with scanf scanf is the analogic input function for printf. var1++. var).0 .var2++). var.5. printf("Floating point numbers: %. var.2e". printf("Now there will be a beep \07 \n"). /* Output: dez: 49 oct: 61 hex: 31 char: 1 */ Example  double f1 = 1. int var2 = 2. /* Output: Column1 Column2 -------------------1 2 2 3 */ 5. printf("%10d%10d\n". interprets then according to the formatting specifications in the control character string and files the resulting values at the addresses. var1.20+e03 */ Example with determination of output width (<Minimum width>) int var1 = 1. Example  int var = 0x31.99 _______________________________________________________ behind point> of the formatting specification. printf("%10s%10s\n". _______________________________________________________ Version IT2.var2).200 1.2. f1. var."Column1".2.f1 * 1000). /* Output: Floating point numbers: 1. printf("--------------------\n"). printf("Hello \n").3f\n %. printf("%10d%10d\n". scanf reads characters of standard output.03.

2. <Conversion d.. s possible for scanf _______________________________________________________ Version IT2. x. <Maximum width> one or several digit max.).03. which should be filed in the read-in values. The address of a variable is obtained by the &-operator. These conversion characters are characters> e. c7. If not indicated.2.. that the l belonging argument (the value to be read in) is of type long int or double.. &ivalue.99 _______________________________________________________ 5.1 Syntactic structure of the scanf function call scanf has the same syntax as printf: scanf("Control character string".2 Structure of a formatting specification for scanf A formatting specification consists of several format elements.. which does not fit the conversion character The letter 'l' The letter 'l' indicates. float flovalue. for example &var is the address of the variable var. argb.Ruth Schubert C-Course 20.0 . f. Example  int ivalue.5.2. arga. scanf delivers back the number of successful transformations or EOF.. These should be indicated directly one after another.5. character number of input decimal number field. The arguments must be pointer. The control character string contains the formatting specifications.2. then the input field is read out until the field separation character (Blank (' ') or Ret '\n') or until the next character. there are the addresses of the variables. The general format of a formatting specification is the following: %<Maximum width>l<Conversion character> The following table indicates what meaning do the individual format elements have: Format element Allowed value Meaning Marker for start of a new % %6 formatting specification. scanf("%d%f". o. &flovalue). 5. Blanks or another random text would be expected again by the user in the input.

The read in character sequence is not finished with the string end character in case of the c-format Blanks can only be read in using the c-format. &feld[0].b.14a 13 [Ret] The assignment to the following variables occurs: var_i = 12. &var_o) . &var_c.2. &b. feld[20]. f = 7. &a.03.Ruth Schubert C-Course 20. &var_f.0. var_f = 3. var_c = 'a'.14. 6 If the percent character receives an *. feld[1] = 'o'. int var_o. &z[0]). 12345 is read over feld[0] = 'W'. When entering: 298 12ab 7612345 Wort i The following assignment occurs to the variables: a = 298. The maximum character number is indicated before c. z[2]. &var_i. then the input field is read over. z[0] = 'i'. When entering: 12 3.99 _______________________________________________________ (see chapter 5. char y. several characters can be read in.1.5. scanf("%3d%x%1lf%c%*5d%4s%1s". For example %*5c reads over 5 characters. &y. _______________________________________________________ Version IT2. var_o = 11. y = 6. b = 4779 (0x12AB). /* octal: 13 */ Example  int a. feld[3] = 't'. feld[2] = 'r'.2 on page 41) Example  int var_i. double f. 7 With the format c. scanf("%d%f%c%o".0 . &f. char var_c. float var_f.

03. var2. var3. &var3. this one must first be cleaned of the following scanf-calls first. &var4)) { printf ("wrong input \n"). var4 *= 16. } } Solution: var_1: 30. printf("varl: %d var2: %d var3: %d\n". which only consist of \n. /* Deletion of keyboard buffer */ if ( 4 != scanf("%d%d%d%d". char zeich. if the format element is not %c. scanf ignores inputs. } else { varl += -var2++ + --var3. using getchar. var_2: 34. var_3: 44 var_4: 10 var_1: 1 var_2: 21 _______________________________________________________ Version IT2. var2. unsigned varl.var4). varl. while ((zeich= getchar()) != 0x20) putchar (zeich). var2 = ++varl + var4. &varl. &var2.Ruth Schubert C-Course 20.0 .varl. printf("varl: %d var2: %o\n".99 _______________________________________________________ scanf leaves the line end \n in the keyboard buffer. var3). Successful test  What does the following program display ? The user introduces: This is the data [RET] 19 33 45 1 [RET] Here is the program: #include <stdio. var2). printf(" Result:\n"). varl = var2 == var3. while (getchar() != '\n'). printf("var4: %x\n".h> void main(void) { int varl.

5.0 */ Also an assignment is a routine and delivers back a value. if (a > c).6 Operators and routines 5.2 C .03.6. sizeof(int). float target. var_1 = funk_xyz (var_2 = 100). multiple assignments are possible through the named feature: _______________________________________________________ Version IT2. x = a & b. 5. Example  int var_1.0 */ Apart from that.1 Overview of operators in C Simple assignment operator (see page 49) arithmetic operators (see page 50) Comparison operators (see page 51) Logic operators (see page 52) Operators for Bit-Manipulation (see page 53) a = b.operators (see page 55) Determining the size of types and variables in bytes through sizeof (see page 56) Conditioned routines8 (see page 56) a += b. this value can for example be transferred during a function call as parameter: float var_2.Ruth Schubert C-Course 20. /* => target is 3. /* =>> the function parameter is of float type and has the value 100.0 .. target = var_1 / 3.6.Specialties Compound assignment operators (see page 54) Increment / decrement .6. (a>b)?(max=a): (max=b).99 _______________________________________________________ 5. The routine is thus automatically converted into the data type of the target variables.... if (a && b).3 Simple assignment operator The operator (variable) left of the equal sign gets the value of the routine on the right of the equal sign assigned. a--. x = a + b * c. var_1 = 11.

int var2 = 3. The result of this comparison is a logical value. Thus for working with logical values with the help of the C-pre-processor. 5. the symbolic names TRUE respectively FALSE are recommended to be defined.5 Comparison operators They compare their operators regarding their numerical values.44 */ + var4 % 3. /* 0 */ Total result is 0 !! For the sequence of a routine assessment.0 . the following instructions are necessary at the beginning of the program or in a central Include: #define TRUE (0 == 0) #define FALSE (0 == 1) Comparison operators are: _______________________________________________________ Version IT2.6.4 Arithmetic operators Addition Subtraction Multiplication Division Modulo-division + * / % Example  int varl = 1. result = (var1 + var2) / 2 /* 2 */ .var3 * var3 /* 1.99 _______________________________________________________ var_1 = var_2 = var_3 = 0. char var4 = '\03'.Ruth Schubert C-Course 20. For this purpose.03. int result. float var3 = 1.6. Thus the used numerical value is compiler dependent under certain circumstances.2. 5. The logical values TRUE and FALSE are demonstrated in C by integer numbers (int). see at "Priority and assessment of operators" on page 57.

. log_erg = (a == b).. if (log_erg) . assigns a the value of b.0 ..6 Logical operators AND OR Negation && || ! These operators determine the truth value of the operators and deliver after a logical connection of the operators a truth value.....03.99 _______________________________________________________ Equal Unequal Greater than Greather than or equal Less than Less than or equal == != > >= < <= Example  if (a >= b)... The instruction if (a=b).Ruth Schubert C-Course 20.6. Attention !!! The assignment operator "=" is often mistaken for the assignment operator "==".. 5. while (sum != MAX). For the sequence of assessing an expression see at "Priority and assessment of operators" on page 57.. the value of b is also interpreted as a logical value and leads in the if-query to the corresponding program jump. Example  _______________________________________________________ Version IT2. Thus the following is valid for the operators' content: • 0 corresponds to FALSE • unequal 0 corresponds to TRUE The result of a logical connection corresponds to that for the comparison operators (see "Comparison operators" on page 51).

Ruth Schubert C-Course 20. /* The lower value four bits are set */ /* The lower value six bits are reset.0 . The right-shift-operations should be used as much as possible only with the variables of the 'unsigned' type. /* The loop is ran through for as long as the content of the variable flag FALSE is */ if ((sum == 0) || (sum == MAX)). This is also valid for char-values ! In case of unsigned-variables. that either zeros are traced from the left side (logical shift) or the one's complements are traced from the left side (arithmetic shift). zeros are drawn in each case.. 5. flag_a = (flag_b && flag_c).. . /* The condition is TRUE..03. */ _______________________________________________________ Version IT2. var = var & ~077.6.99 _______________________________________________________ if ( (a > MIN) && (a < MAX)). .. because otherwise a machine dependent leading sign handling occurs.7 Operators for Bit-manipulation Bit-wise Bit-wise Bit-wise One's complement Left-Shift Right-Shift AND & OR EXCLUSIVE-OR ^ ~ < >> These operators can of course not be used with the floating point numbers. A left shift draws a zero. in each case. if also a is greater than MIN as well as less than MAX */ while (!flag) . Example  model_1 = model_in | 0x0f. This can lead to the fact.

Ruth Schubert C-Course 20.99 _______________________________________________________ /* Additional comparison: var & 01777700 is machine dependent.03.8 Compound assignment operators The programing practice often needs instructions of the following type: y = y <operator> x.0 . assumes. For the example: y += x. The following compound assignment operators are available: • += • -= • *= • /= • <<= • >>= _______________________________________________________ Version IT2.6. value = value >> 2. that int assigns two bytes. C allows here a more compact writing type: y <operator>= x. /* the content of the value is shifted to the right by 2 bit positions */ Attention !!! The operators for bit by bit AND/OR-connection are often mistaken for the operators to the logical AND/OR-connection: • logical connection: (1 && 2) gives 1 and(1 || 2) gives 1 • bit-by-bit connection: (1 & 2) gives 0 and (1 | 2) gives 3 5. */ unsigned value. Example  y = y + x.

corresponds to count = count .Decrement Examples: index++. value /= divisor. the increase or reducing of the content of a variable by 1 can be simply realized in C through the increment.9.03. 5./ decrement operators. 5. The increment-/decrement operators can be indicated before or after the variables.6. respectively count -= 1. flags ^= comparison model. model <<= mask. corresponds to var1 = var1 * (var2 + var3*2). rest %= 3.Ruth Schubert C-Course 20. count--. respectively index += 1.6.1 Prefix quote _______________________________________________________ Version IT2. model <<= 3.9 Increment and decrement operators An often used instruction.1.99 _______________________________________________________ • &= • |= • ^= Example  var1 *= var2 + var3 * 2. corresponds to index = index + 1.0 . device_status |= 0x0f. • ++ Increment • -.

The increment/ decrement operators are often used in connection to field-or loop-indexes.0 . value += var * ++xyz. xyz = 3. var = 2.Ruth Schubert C-Course 20. var = 2. then the variable is first incremented or decremented and then inserted in the routine. 5. This type is determined in the include file stddef. Example  value = 1.9.sizeof(int)). 5. xyz = 4. _______________________________________________________ Version IT2.10 sizeof The sizeof-operator determines the size of an object in bytes. then the variable in the routine is first inserted and finally incremented (decremented) Example  value = 1. var = 2. xyz = 3. xyz = 4. The result of the sizeof-operator is of size_t type. value = 7. value += var * xyz++.03.2 Postfix quote When indicating the operator after the variables.6.h. var = 2.99 _______________________________________________________ When indicating the operator before the variables. value = 9.6. The object can be:  variable a a field a structure the name of a data type (also typedef-agreements) Example  printf("allocate int-numbers %d Bytes".

costs) > 0" is fulfilled.03.6.12 Priority and assessment of operators The sequence with which the individual operations of a routine are performed..costs) > 0) ?GOOD:BAD. otherwise success receives the content BAD. else success = BAD.11 Conditioned routines Conditioned routines represent a compact writing type for the assessment of conditions.99 _______________________________________________________ 5. is determined in the following table: Highest priority Conclusion () [] -> .Ruth Schubert C-Course 20. then the symbolic constant GOOD is assigned to success. First <condition> is assessed. If the routine is TRUE then <true_routine> is the result of the conditioned routine. then <false_routine> delivers the result of the conditioned routine. Syntax <condition>?<true_routine>:<false_routine>. Example  success = ((turnover . If the condition "(turnover . From the left ! ~ ++ -. 5.6.0 . The conditioned instruction replaces simple if-queries: if ((turnover .costs) > 0) success = GOOD. If <condition> FALSE.(<typ>) * & sizeof From the right * / % From the left + From the left << >> From the left < <= > >= From the left == != From the left & From the left ^ From the left | From the left && From the left || From the right _______________________________________________________ Version IT2.

res. A routine always delivers a value.0 . which should be avoided Example  Example a = 3. Example for routines.....13 Routines A routine is a construction of operands. but the programmers always make mistakes. The safe method is to set brackets where you can. . like for example as an argument to a function..03.. operators and round brackets. .99 _______________________________________________________ ?: = += -= etc (see "Simple assignment operator" on page 49 and "Compound assignment operators" on page 54) lowest priority From the right From the left Hot tip  It is better not to learn this by heart .6. 5. res = sqrt(value = 2).. the variable contents can be modified during the processing of a routine (so-called "side-effects"). _______________________________________________________ Version IT2. nested allocations and the increment / decrement operators. A routine can thus be found everywhere. Thus the routine var = 100 does not only allocate the variable var the value 100.. If a routine causes side effects.the compiler can master these priority sequences very easily.. where the resulting value matches. then the sequence in which the values are stored (compiler dependent!) can be crucial for the result.. because this way the intentions are absolutely clear.6. but delivers itself the value of 100. Example  double value. 5.14 Side effects in routines Through function calls.Ruth Schubert C-Course 20.

The highest priority of && to || is not important here!! Another example: x = 0. y = 1. c.0 . (( a = 3) * (a *= 3)). z = 1. Example  Example Would be better x = y = a = ++x x = y = b = ++y a = ++x z++. z = 1. Thus in the above example.99 _______________________________________________________ z = a / ++a. z = 1. the assessment is interrupted. Variable a has either the value of 9 or the value of 12.03. y and z were also not modified here ! _______________________________________________________ Version IT2. Routines with logical operators (&& or ||) are assessed from the left to the right until the truth value is agreed. a++. && z. a * c. The variable b has either the value 27 or 36. Would be better It is not defined. a * 3. when the value for "a" is taken from or stored into the respective memory cell. a = x && (y++ || z++). a = 3. the example thus shows surely. 3. Example  Example Would be better a b a c b a = = = = = = 4. As soon as the result of the logical routine is agreed. the variables y and z were never incremented. || b. z = a / (a + 1).Ruth Schubert C-Course 20. whether the dividend is 3 or 4 (compiler dependent!). || ++y && z++.

/* what does value_4 contain? */ _______________________________________________________ Version IT2.0 . · in routines with logical operators. value_3. value_2 and value_3 contain? */ 1. 4 value_1 == (value_2 = value_3 + 1). value_1 = -20 / 4 + 2 * 4. /* what do value_l. 5. value_3 = 0. (The increment / decrement operators imply an assignment to the variable!!) ! Successful test ´ Answer the questions in the comment lines of the final C program ! It is assumed. /* what does value _1 contain? */ 15 value_1 += value_2 = value_3 = 4. 4. the integrated assignments should be avoided. 4. /* what do value_l. /* what do value_l. value_2 and value_3 contain? */ 19. 4 (value_1 gets nothing assigned !) value_1 = 1. 4 value_1 = value_2 == value_3.6.14. value_4 = value_1 || ! value_2 && value_3.99 _______________________________________________________ 5. then this variable is not allowed to be used a second time in the routine. /* what does value_1 contain ? */ 3 value_1 *= 3 + 2. value_4. value_2. the following rules must be set up: · if an assigment to a variable appears in a routine. that for the used compiler TRUE is set as 1 and FALSE as 0! void main(void) { int value_l.1 Rules for avoiding side effects In conclusion. value_2 = 2. value_2 and value_3 contain ? */ 1.Ruth Schubert C-Course 20.03.

value_2 += -value_1++ + ++value_3.Ruth Schubert C-Course 20.2 if-branching 5. value_2 = value_3 = 4. value_ = 2.7. while and for . /* what do value_l.7 Control structures 5. This is used to: · define a function body. · conclude several instructions depending on if.0 . which follows upon if is assessed.03. value_3 = 3. which closes a block. there is never a semicolon – at least not in C and except for structures (see "Simple structures" on page 122) 5.5.7.2.1 General form of the if-branching Syntax if (<routine>) <instruction_1>.7. value_2 and value_3 contain? */ 2. value 4 = ((value_1 >= value_2 >= value_3) ? 1 : 0 ).1 Blocks Agreements and instructions are gathered to a block using accolades. The routine <routine> closed in brackets. /* what does value_4: contain ? */ 0 } 5. then _______________________________________________________ Version IT2. else <instruction_2>. After the right accolade. If the routine gives a value unequal 0 (TRUE).4 value_1 = 5.99 _______________________________________________________ 1 value_1 = 1.

in the other case. then the instructions must be summarized to a block. thus it must be considered.7. If the routine gives 0 (FALSE). Should anything be modified in this allocation of else-instruction.2. the program is immediately continued with <instruction_2>.2 if-instruction without else-branch The else-branch of an if-instruction can be missing: if (<routine>) <instruction_1>. 5.2. If more than one instruction must be performed in a branch. for which there is no else-part yet.99 _______________________________________________________ <instruction_1> is performed. <instruction_2>. then <instruction_2> (of the else-branch) is performed.3 Nested if-instructions if-instructions can be nested.Ruth Schubert C-Course 20. In this case <instruction_l> is performed.03. else max = a. that an else-instruction always belongs to the previous if. if <routine> is TRUE.0 . then this is reached through blocking: Example  if (a > b) { if (c > a) _______________________________________________________ Version IT2. 5. Example  if (a > b) if (c > a) max = c.7.

5.Ruth Schubert C-Course 20.99 _______________________________________________________ max = c.4 else-if-chains If a decision must be taken from several alternatives. Example  /* Function: The program reads a temperature value from standard input and gives according messages regarding the status of water in case of this temperature */ #include <stdio. scanf("%f". printf("Please enter temperature: "). etc. else if (<routine_2>) <instruction_2>. if (temp <= 0) printf("\n the water is frozen \n"). Syntax if (<routine_1>) <instruction_1>. else if (temp == 4) printf("\n at this temperature the " "water is liquid and has the " "highest density \n").2.&temp).03.7. else if (<routine_3>) <instrucion_3>.0 .h> void main(void) { float temp. } else max = b. then this will happen through else-if-chains. else <instruction_4>. else if (((temp > 0) && (temp < 4)) || ((temp > 4) && (temp < 100))) _______________________________________________________ Version IT2.

7.   true if (<routine>) { <instruction_1>. if <routine> is true. else printf("\n steam is forming\n"). that an if-structure in the code is however correctly indented in the code. then only an empty instruction is performed instead of <instruction_1> (common error source !).2. <instruction_2>. _______________________________________________________ Version IT2. } In this case <instruction_2> is only performed.03.99 _______________________________________________________ printf("\n the water is in liquid " "state\n"). Attention  In the C-programs.0 . else if (temp == 100) printf("\n the water is boiling\n").5 Some common errors when handling if-queries Attention  If there is a semicolon behind the if-routine indicated in the brackets.. but it is written syntactically incorrect.. this bad habit should be avoided as much as possible.Ruth Schubert C-Course 20. False if (<routine>) <instruction_1>. } 5. <instruction_2>.. Attention  Another common error source is. This error is easily overseen when reading the program listings. In this case <instruction_2> is always performed. a numeric verification to 0 respectively unequal 0 is often replaced by the logic interpretation of the value: if (var) instead of if (var != 0) if (!var) instead of if (var == 0) Because this clearly deteriorates the program's readability.

. if the result of a routine matches with one of several constant values.. Syntax switch (<routine>) { case <const_l>: <instructions_1>. then nothing will be done.1 Basic form of switch-instruction Using the switch-instruction it is checked. The case-constants must either be of int or char type. . default: <default_instructions>.3. If default is missing.7.. } The <routine> of the switch-instruction is assessed and compared with the case.7. then the <default_instructions> are performed until the next break-statement or the end of the switch-block.h> _______________________________________________________ Version IT2. Even if default is at the beginning. Attention  The sequence of the case-branches and the default-branch has nothing to do with the sequence in which the comparison of <routine> with <const_1>. occurs. If a match is found: (<routine_n> == <const_n>) Then the instructions <instructions_n> are performed up to the next break-statement or the end of the switch-blocks. case <const_2>: <instructions_2>: break.constants <const_1>.3 switch-instruction 5. Of course there can also be constant routines. <const_2> etc.99 _______________________________________________________ 5.Ruth Schubert C-Course 20.0 .03. all comparisons are performed ! Example  /* Function: The program reads a number between 1 and 6 as a note of standard input and displays the corresponding conversion of the note on standard output: */ #include <stdio. <const_2> etc. If no match is found. break. break.

break. break. break. scanf("%1d". case 4: printf("\n sufficient \n"). case 3: printf("\n satisfactory \n"). switch (note) { default: printf("\n Input error \n"). case 1: printf("\n very good \n"). case 6: printf("\n insufficient \n").Ruth Schubert C-Course 20. case 2: printf("\n good \n"). break.03. printf("\n please enter note:").&note). break.99 _______________________________________________________ void main(void) { int note. break. break.0 . case 5: printf("\n poor \n"). } } _______________________________________________________ Version IT2.

h> void main(void) { _______________________________________________________ Version IT2. break.0 . case 4: case 5: case 6: printf(" this note is not " "acceptable \n"). Attention  This is an often error source.7. This feature is necessary to be able to summarize several case-instructions with the same program handling.99 _______________________________________________________ 5.03. Example  switch(note) { case 1: case 2: case 3: printf(" this note is ok \n").Ruth Schubert C-Course 20. break. break. Successful test  Explain the function of the following program! Give an example for the program flow! #define EXIST_MIN 1000 #define EXIST_GUT 10000 #include <stdio. then the program flow runs in the instructions of the next case. default: printf(" input error \n").3.2 Variant with partly missing break-instructions If break is missing as a finalization of the case-instructions.

99 _______________________________________________________ int salary. if (salary < EXIST_MIN) { printf("\nYou are a poor bastard \n"). salary. scanf("%d".0 .&salary). } else { printf("\nYou don't have to die of hunger \n"). printf("\nenter monthly salary: "). "monthly salary".Ruth Schubert C-Course 20.03. category = 'm'. char category. category = 'r'. printf(" %20d %20d %20ld\n". "yearly income"). (salary/30). salary*12L). } switch(category) { case 'a': printf(" Money alone does not make one " "happy \n"). "daily salary". category = 'a'. _______________________________________________________ Version IT2. } else if (salary > EXIST_GOOD) { printf("\nYou are to be envied \n"). printf("\n %20s %20s %20s\n".

calculated from the entered monthly salary. The user is prompted to enter by the message Enter monthly salary : Input: an integer number (-32768 to +32767) Thus the daily salary.7. In addition. the output of a 2-line comment regarding the salary occurs. default : printf(" this cannot be\n").03. break. break. } } Solving the successful test The program displays the daily salary calculated from the read in montly salary and the yearly income with two comment lines.99 _______________________________________________________ break.Ruth Schubert C-Course 20. case 'r': printf(" Money has no smell \n"). are displayed in columns with a corresponding title. break. the entered salary is classified into one of 3 categories: • Category 'a': salary < EXIST_MIN • Category 'm': EXIST_MIN <= salary <= EXIST_GOOD • Category 'r': salary > EXIST_GOOD Example: Enter monthly salary: 900 Daily salary monthly_salary yearly-income 30 900 10800 You are a poor bastard Money alone does not make one happy 5. case 'm': printf(" Christmas comes but once " "a year \n"). After the output of an empty line.4 while – loop _______________________________________________________ Version IT2. the entered monthly salary and the calculated yearly income.0 .

then the blocking can be renounced to ({}). } } _______________________________________________________ Version IT2. celsius).99 _______________________________________________________ 5.0) * (drive . It starts with 0 F and ends with 300 F. /* Loop body */ } <routine> is assessed before each loop runthrough. The loop is only ran through. the increment is 20 F. If the loop body consists only of one instruction. drive.1 Standard form of a while-loop Syntax while (<routine>) { <instruction>.0 .1f \n".03.0 / 9.4. printf("%4d %6.Ruth Schubert C-Course 20. Example  /* The program displays a conversion table of Fahrenheitto Celsius temperatures on the standard output. */ #define LOWER 0 #define UPPER 300 #define STEP 20 void main(void) { float celsius. int drive = LOWER. while (drive <= UPPER) { celsius = (5.0).7.32. if <routine> displays a value unequal 0 (TRUE). drive += STEP.

The character is displayed again on standard output.4. the semicolon is necessary behind the bracketed do-while-condition.99 _______________________________________________________ 5.2 while-loop with empty loop body The loop body can however remain empty: /* Emptying of keyboard buffer: */ while(getchar() != '\n'). It is used if a loop must be ran through at least once. If <routine> gives a value unequal 0 (TRUE). For the do-while-loop. do { _______________________________________________________ Version IT2.7.5 do .0 .while – loop Syntax do { <instruction>.. The do-while-loop is used much more rarely than the whileloop. } while (<routine>). 5.03. then the loop is rant through again..7. the loop condition <routine> is checked after each loop run-through. The loop body is thus processed at least once. Attention  As opposed to the while-loop... Attention  An often error cause is the accidental setting of a semicolon Behind the bracketed while-routine.Ruth Schubert C-Course 20. Example  /* At least 1 character is read in by the standard input. */ . The reading in is interrupted if a '#' is entered. It can easily come to endless loops.

int drive = LOWER. for (drive = LOWER. • <routine_3>: Re-initialization of loop. then the ({}) blocking can be missing. It starts with 0 F and ends with 300 F. drive += STEP) { celsius = (5. } If the loop body consists only of one instruction. then the loop is ran through. the routine is assessed before each loop run-through. The three routines of the for-loop have the following meaning: • <routine_l>: Loop initialization. • <routine_2>: Run through condition of loop. usually initialization of run variables.99 _______________________________________________________ char = getchar(). 5. which must be performed for each loop run-through.0) * drive .32. the increment is 20 F.Ruth Schubert C-Course 20. actions. <routine_3>) { <instruction>. <routine_2>. } while ( char != '#'). If it shows a value unequal 0 (TRUE). normally incrementing or decrementing the run variables.03. drive <= UPPER.7.0 . drive. celsius).6 for – loop Syntax for (<routine_l>. _______________________________________________________ Version IT2. Example  /* The program displays a conversion table of Fahrenheitto Celsius temperatures on standard output.0 / 9.1f \n". putchar (char). */ #define LOWER 0 #define UPPER 300 #define STEP 20 void main(void) { float celsius.0). printf("%4d %6.

} or: for (. i < MAX.03... */ /* .. then the result is an endless loop.. i++) { field[i] = getchar(). Example  for (i = 0. Example  for ( i = 0. if (field[i] == '*') break. k += 2) { field_1[i] = field_2[k]. /* Each second element of 'field_2' is transferred to field_1 */ } /* This condition.... } <routine_1> and <routine_3> can consist of several instructions.. If for example <routine_2> is missing. i++. which are separated by a comma.leads to the interrupt of the endless loop */ _______________________________________________________ Version IT2.) { char = getchar(). } The endless loop is also often realized by: while (TRUE) { . k = 0.99 _______________________________________________________ } } Each of the three routines can be missing.Ruth Schubert C-Course 20.. putchar(char).0 .

7.Ruth Schubert C-Course 20. <routine_3> is performed.i). to quit switch-blocks. i < 20.7. The continue-instruction can not be used. printf("%d ". /* Output: 1 2 3 4 */ 5.0 . <routine_2> is assessed and in case of TRUE the next loop run through is started. the loop condition is assessed and processed in the TRUE-case of the next loop run-through.03. } printf("\n"). break mostly serves for making the loop condition more visible.8 continue . /* Output: 1 2 3 4 6 7 8 9 11 12 13 14 16 17 _______________________________________________________ Version IT2. i++) { if ((i % 5) == 0) break.i). Example  for (i = 1. For loops. In case of for-loops.or do-while-loops.instruction The break-instruction leads to leaving the inner loop (while.Instruction The continue-instruction forces the interruption of a loop run-through. Example  for (i = 1.7 break. For while. } printf("\n"). i++) { if ((i % 5) == 0) continue. do-while or for-loop) or leaving a switch-block. In case of switch-blocks (see "switch-instruction" on page 65) the breakInstruction is indispensable. i < 20. printf("%d ".99 _______________________________________________________ 5.

.9 goto . if for example several nested loops must be quitted instantly...... .. .. _______________________________________________________ Version IT2.. When reaching the goto-command.) { for (. the same rules are applied as for variable names. Brands do not need to be extra defined.) { . <instructtion_x>. <mark>: <instruction_y>..99 _______________________________________________________ 18 19 */ 5. for example.. For brand names.... goto <mark>.Ruth Schubert C-Course 20.. error: printf("catastrophe !!! \n").....03.7. to initiate an error handling. if (catastrophe) goto error..Instruction / Brands Syntax .) { for (.0 ..... the wird die <instruction_x> instruction is not performed anymore.. } } } . instead it is jumped to mark <mark> and the <instruction_y> instruction is the next to be performed. The goto-instruction should be used as rarely as possible !!!!! Example: while (. The use of the goto-instruction is only allowed...

Ruth Schubert

C-Course

20.03.99

_______________________________________________________

5.8 Data type conversions 5.8.1 The implicit conversion of the data type In C there is the possibility to link operands of different data types with each other. Different rules for implicit type conversion are applied then. Rule 1: The "lower" type with the lower bit width is converted into the "higher" type with the higher bit width. char/shortintlongfloatdoublelong double The result of a routine always receives the operand type with the highest bit width. Example  int z1 = 30000, z2i = 30000; long z2l = 30000; long erg1, erg2; erg1 = z1 + z2i; printf("erg1: %ld \n", erg1); /* Error due to int-overflow:"erg1: 5536" */ erg2 = z1 + z2l; printf("erg2: %ld \n", erg2); /* Addition with longExactity:"erg2: 60000" */ Rule 2: During assignment, the result of the routine on the right of the assignment operator is converted into the type of the target variables. Modern compilers generate a warning in case the type of the target variables is not able to record the routine result with full accuracy. Example  int full; full = 20.0 / 3.0; printf(" %d \n", full); /* output: 6; BORLAND

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
- Compiler generates a warning "Conversion may lose significant digits" */ char c; c = 0; /* instead of "c = '\0' */ Rule 3: Floating point calculations are always performed with double exactness. 5.8.2 The explicit conversion of the data type If the rules of the implicit data type conversion are not sufficient, then there's the possibility of the explicit type conversion with "Casts". A "Cast" is a type designation set in brackets, which precedes the operand. Syntax (<Type designation>)<routine> The cast determines the routine type. The cast operator has lost significance due to the introduction of function prototypes in Standard-C. (Function prototypes enable an implicit type adaption of the parameters) Example  float value; int number; .... printf("(int) value: %d\n", (int)value); printf("number/2: %f\n", ((float)number)/2); Example  long result; int number1, number2; .... result = ((long) number1) * number2;

Attention 
Carelessly set casts bring more programming errors than any other construct! The reason is, that a cast is a type of agreement declaration of the programmer in regards of the compiler, to handle a routine in a certain way – this way all type

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
verifications are thwarted by the compiler! 5.9 Fields (Arrays) 5.9.1 Unidimensional errors To access a group of same-type elements in an efficient way, these objects are gathered in a field. Definition of a field <typedesignation> <fieldname> [<number_of_elements>]; Example  /* Definition of a field, which consists of 100 intelements: */ int field[100]; The field size indicated in a field definition must be a constant routine ! The elements of a field could be: · scalar objects of all types · other fields (see "Multi dimensional errors" on page 80) · Structures (see "Definition of a structure field" on page "125) · Unions (see "Unions (Variants)" on page 174) · Pointers (see "Pointer fields" on page 93) Example  char c_field[SIZE * 2]; float flo_field[FLOAT_NUMBER]; Field elements are handled as individual variables of the according data type. An element is accessed using an index. The index is indicated in square brackets after the field name.

Attention 
The index runs from 0 to field size minus 1 !! By selecting an unallowed index it is immediately possible to destroy other variables or even program parts of the memory.

Example 
#define C_NUMBER 10 /* Important ! Field size ALWAYS define centrally

_______________________________________________________ Version IT2.0

i < C_NUMBER. int i.0 .Ruth Schubert C-Course 20. j.03. /* all elements of the field are to be allocated with 'a' */ The elements of a field stand one after another in the memory! 5.2 Multidimensional fields Multidimensional fields are defined by listing the individual dimensions one after another in square brackets. i < output [j][i] = ROWS. for (j = 0. Row 1 should contain numbers ranging from 0 to 4. row 2 should have numbers from 5 to 9: '0' '5' '1' '6' '2' '7' 5 '3' '8' '4' '9' #define ROWS 2 #define COLUMNS char c = '0'. Example  Example for a field. which should assimilate the characters for an output field of 5 columns and 2 rows. j++) COLUMNS. i++) c++. The memory allocation for this example looks like the following: Address Content Symbol adr 0x30 output[0][0] adr+1 0x31 output[0][1] adr+2 0x32 output[0][2] adr+3 0x33 output[0][3] adr+4 0x33 output[0][4] adr+5 0x33 output[1][0] _______________________________________________________ Version IT2. j < { for (i = O. for (i = 0.9.99 _______________________________________________________ ! */ char c_field [C_NUMBER]. int i. i++) c_field[i] = 'a'.

03. {'5'. _______________________________________________________ Version IT2. 3500. '6'. included in accolades and 3. Example  float threshold_values[] = {12. 2. The initial values are 1. '8'.99 _______________________________________________________ adr+6 adr+7 adr+8 adr+9 0x33 0x33 0x33 output[1][1] output[1][2] output[1][3] output[1][4] Hot tip  To be remembered: the last index is the fastest to run through. '4'}. '9'}}. which pre-allocates the fields with meaningful values.3 Initialization of fields at definition Fields can be pre-allocated with values already during definition. 2000. 5. '2'.0 .4. The field size is determined according to the number of initial values.9. here: 4.Ruth Schubert C-Course 20.5. 1100. Example  char output[2][5] = {{'0'. Example  int turnover[5] = {1000. '3'. '7'. 0. an additional code must be written.5e03}. 3. in this case. separated by commas. 7000}. '1'. attached through an allocation marker to the array definition. 120e-2.

A variable can be accessed indirectly using a pointer.'c'.'n'. which are very hard to find.'h'.' '. where they are necessary.'s'.'l'. which contains the address of another variable. */ 5.Ruth Schubert C-Course 20. Structures (see "The '->' . _______________________________________________________ Version IT2.'b'. Attention  Pointers can also be misused and they can include errors.0 .'e'.operator" on page 124) and dynamic memory (see "Dynamic memory management" on page 118) The pointer concept is relatively easy to understand for assembler-programmers because: A pointer is a variable. Example  char errmessage[] = {'f'.'a'. simply: char errmessage[] = "wrong input". /* Exception: characterFields can be initialized With character strings without accolades.'a'. however under no circumstances where they are unnecessary! Pointer types usually appear with · Function parameters (see "Function parameters as an address ("call by reference")" on page 100). · Fields (see "Pointers and Fields" on page 87).10 Pointer The handling of pointers is essential in C philosophy.'i'. The following must be valid when handling pointers: to be used there.'\0'}. Due to their outstanding meaning in C programming it is necessary to deal with pointers for a long time.03. 'E'.'g'.'e'.99 _______________________________________________________ The accolades which include the row elements are there to give a better overview and are not obligatory.

/* Definition of a pointer on an intvariable */ /* Definition of a pointer on a charvariable: */ char *char_poi.Ruth Schubert C-Course 20. /* The pointer "var_poi" gets the address of "var" assigned: */ var_poi = &var. *var_poi = 9.0 . var_2. var_2 = *var_poi. Example  int *intpol.10.10. Pointers with the '*'-operator can appear in routines. wherever there can be simple variables found as well. Example  int var_1. *var_poi. The variable can be read or modified this way. 5. var_poi = &var_1.3 The content of a memory cell addressed over a pointer The content of a variable named over a pointer is reached with the help of the indicating operator '*' (referencing). Example  int var. /* works like: var_1 = 9 */ /* works lile: var_2 _______________________________________________________ Version IT2.99 _______________________________________________________ 5. *var_poi.03. 5. It is defined by setting a star * before the name.2 The address of a variable The address of a variable is received by indicating the address operator & before the variable name.10.1 Definition of a pointer A pointer must be agreed with the target object type.

10.. int y = 2.. 7000 7002 ... point_point_z Address 1000 1002 . point_y = &y..... For this case.4 Example of a memory allocation with variables and pointers Memory content according to the following instructions: int x = 1. 7000 . there is the zero pointer ZERO defined in the standard-include stdio... Variable x y . (*var_poi) *= 2. point_z = &z. *point_z.*/ /* works like: var_1++. 5. **point_point_z. Point_z . 9200 Memory content 1 2 ....03.99 _______________________________________________________ = var_1... here: Needs brackets */ /* works like: var_1 = var_1 * 2.0 . 9100 If a pointer (for example in a function) can get no defined value assigned.Ruth Schubert C-Course 20. int *point_y.. point_point_z = &point_z. Example  _______________________________________________________ Version IT2. int z = 3. 9100 . then it should never be left with a random content (points to a random location) . z Point_y ... */ (*var_poi)++.h. 3 1002 .

Ruth Schubert C-Course 20. number = point_1 . /* poi is further positioned by 3 elements */ • Increment poi++.point_2. Allowed operations with pointers: · Addition of an integer number value (int-routine) int wert = 3. The result is thus an int-number.03. /* number = Number of elements between the two pointers plus 1 */ • Comparison between two pointers. • Subtraction of an integer number value /* poi is positioned back by two elements: */ poi -= 2.99 _______________________________________________________ if (error) poi = ZERO. which corresponds to the number of elements between the two pointers plus 1.10. for each calculation.5 Pointer arithmetics Pointers can also be used to do arithmetic operations. • Decrement poi--. By subtraction a number is determined. Pointers can be compared with the following comparison operators: ⇒> _______________________________________________________ Version IT2. 5.0 . poi += value. /* poi is positioned back by one element */ • Subtraction of two pointers of the same type. this is necessary if the pointer must indicate to other variables.

point_y): (point_ypoint_ x). printf(" %d \n". /* 14 */ pointer = &number_l.Ruth Schubert C-Course 20. number_2). /* 124 */ } _______________________________________________________ Version IT2. pointer = &number_3. number_1). /* 126 */ number_2 = *pointer / 2 * 7. --(*zeiger)). *pointer). *pointer. printf(" %d \n".0 . number_2. printf(" %d \n". *pointer.03.h> void main(void) { int number_1. number_1 = number_2 * number_3. printf(" %d \n". Successful test  What does the following program display on standard output ? #include <stdio. /* 441 */ (*pointer)--. number_3. /* 125 */ zeiger = pointer. number_3). number_1 = 5.99 _______________________________________________________ ⇒ >= ⇒< ⇒ <= ⇒ == ⇒ != Example  number = (point_x > point_y) ? (point_x. *pointer = number_1 + number_2. number_2 = 9. printf( " %d \n".

Example  float *flo_po.10. Example  3 possibilities of allocating a field with 0. poi++) *poi = 0. /* 3. i++) field[i] = 0. Each operation with fields can also be formulated with pointers.03. /* 1. /* 2. 5. i < 10. The field name without index is a pointer on the first element of the field. Also valid for multidimensional fields! In a field int field[10].6 Pointers and fields Pointers and fields are strongly connected in C. int i.99 _______________________________________________________ 5. /* The i_po pointer is further positioned by 200 bytes: _______________________________________________________ Version IT2. int field[10].Ruth Schubert C-Course 20. /* The flopo pointer is further positioned by 4 Bytes */ int *i_po.1 Connection between physical address and pointer arithmetics The pointer arithmetic goes depending on the memory necessity of the addressed object. if field is a pointer on field[0]. A pointer on a field element is set when incrementing on the next field element.0 . poi < (field + 10). i++) *(field + i) = 0.6. i < 10. flopo++. Possibility: */ for (i = 0. Possibility: */ int *poi. Possibility: */ for (i = 0. for (poi = field.10.

"helau").7. o. 1. initialized with the characters. character strings).10. 5. "hello". Because the char-field has no name in this case. The first pointer addresses a character string. transfers to the standard function printf the string "hello" respectively a pointer on the character string h.Ruth Schubert C-Course 20.0 . \0 "hello" is a char-pointer The instruction printf(" %s %s %s".03.1 Strings as function parameters In the previous examples strings were used in case of printf function calls. the _______________________________________________________ Version IT2. e. When defining char-fields.pointer (Strings) A special use of char-pointers are the "character-strings" (string literals. Strings are used as: Function parameters (see "Strings as function parameters" on page 89) Assignment to char-pointers (see "Strings in assignments to charpointers" on page 90) • Initial values for char-fields (see "Strings at the initialization of char fields" on page 91) 5.10. which are closed between high commas. The content of a character-string is a sequence of characters which is limited by the limit character '\0'.99 _______________________________________________________ */ i_po += 100. the string itself is a char-pointer! It is shown by a character string closed between double apostrophes. 1. it must be considered. which should take up a character string. transfers thus to the function printf four char-pointers. that: Field length = number of characters +1 limitation character The type of a string is: char-field. The instruction printf("hello"). which contains the formatting characters. "halli".7 char .

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
following three pointers are the strings to be displayed (the format element %s requires an address as a corresponding parameter!).

5.10.7.2 Strings in assignments to char-pointers A char-pointer can get a string assigned during definition or during the program flow. Example  char *cpoi; c_poi = "hello\n"; printf(cpoi); Example  Initialization of a field of char-pointers char *t_zeit[] = {"Morning", "Noon", "Evening", " Night" }; Thus a field of char pointers is made, which point out to the indicated strings.

Zeit = time Morgen = morning Mittag = noon Abend = evening Nacht = night

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
There are different possibilities to access the strings Example  /* output: noon: */ printf("%s\n", *(t_zeit +1)); /* output: noon: */ printf("%s\n", t_zeit[1]); /* output: n: */ printf("%c\n", *(*t_time+2)+3)); /* outout: n: */ printf("%c\n",*(t_time[2]+3)); 5.10.7.3 Strings when initializing char-fields char-fields can only be initialized at string definitions; Allocations during the program flow are not allowed. Example  char c_field[6] = "Hello"; char message[] = "wrong input";

5.10.7.4 Standard functions for string handling Several functions are available in the C standard library for handling character strings (see "String processing" on page 177).

Examples 
#include <string.h> char *target, *source; char *str1, *str2; strcpy (target, source) strcpy(cfe, "Hello"); strcat (target, source) Copies the source string to the address, which indicates target. Copying is ended through the string end character '\0'. Appends the source string to the target string

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
strncat (target, source, length) strcmp(str1, str2); the source string is appended with length Byte respectively until the string-final character to the target string. Compares str1 with str2 character by character, according to the ASCII-character set and delivers the following values back : 0 if str1 == str2 >0 if str1 > str2 <0 if str1 < str2 Searches in the string transferred in str1 for the indicated characters (here: c). The search starts at the beginning of the string.It is ended at the first appearance of the c character or at the string end character '\0'

strchr(str1,'c');

Example 

char *src, *dest; /* Formation of strcpy-function */ /* src the pointer should be on Source-String,*/ /* dest the pointer should be on target string */ while ((*dest++ = *src++)

!= '\0'); 5.10.8 Pointer errors Pointers can be gathered in a field. 5.10.8.1 Definition of a pointer field int *poifeld[3]; /* defines a field of 3 intpointers */ 5.10.8.2 Assignment of an address to a field element poifeld[i] = &var; /* corresponds to *(poifeld +i) = &var; */

_______________________________________________________ Version IT2.0

10.10.1 Definition int var.Ruth Schubert C-Course 20. in case of pointer fields.7.9. */ **point_point = 100. poi = field.2 Allocation point_point = &poi. */ /*double referenced corresponds to var = 100 or *poi = 100. 5. /* simply referenced According to. void main(void) { int *poi. 5.10.9.3 Access *point_point = &var.5.6. *poi. a pointer on the field element 0.03. int **point_point. */ The name of a pointer field is like in other fields.9. Successful test  What does the following program display? #include <stdio.h> int field[10] = {1.99 _______________________________________________________ 5.9 Pointer on pointer Pointer on pointers are especially used in parameter transfer to functions (see "Argument transfer to the main-function" on page 101). **poipoi.4.9.2. it is thus a pointer on a pointer. i. 5. 5.10.10. /* corresponds to **(poifeld+i) = 0.: poi = &var. _______________________________________________________ Version IT2.3.3 Access to an addressed object *poifeld][i] = 0.8.0 .8.10}.

In the present examples and exercices there were some functions called already and always a function which defines the main-function. The source files are translated separately. C-programs can be divided into several source files. function name and the parameters.i <5.1 Function definition The function definition consists of the function head which describes the function type.0 . In general.11.Ruth Schubert C-Course 20. Syntax <type> <functionname> (<parameter>) { <local symbols> <instructions> } Description • <typ>: This name indicates the type of the function's return value. } } Result: 1 3 5 7 9 5. which is located in brackets behind the return-instruction. this means the type of routine. (see "Result transfer through the return value" _______________________________________________________ Version IT2. C-programs consist of several small functions and not a few large functions.11 Functions Functions enable the separation of a complex program into individual manageable units. The called functions were functions from the standard library like for example printf() or scanf(). if necessary. poi += 2. for (i=0.03. 5. **poipoi). the resulting object modules are set and bound in libraries. and contains the function body.99 _______________________________________________________ poipoi = &poi. Which has the definition of the local variable and the instructions of the function. i++) { printf(" %d".

func(value. in this case. erg = flo_func(var_1. which is included in round brackets.11. A function call can be found everywhere. then the int type is taken as a default value. If the type name is missing. value2). Parameters can be missing. _______________________________________________________ Version IT2. if a function returns a value where a variable or a constant of the same type could be found.200)). func_x(value1. printf("Result: %d".99 _______________________________________________________ on page 99). Example  int var_1. int p2) { float xyz. float erg. The parameters are indicated with their type. The current paramteters for the function call must correspond regarding the number and type with the formal parameters of the function definition (see also "Parameter transfer" on page 99). they are separated by comma. Example  float flo_funk(int p1. func_x(func(a.b) * 100.03. } 5.2 Function call A function is called by indicating the function name and through the current parameters listing. Example  value = func(a. • <parameter>: The parameter list is indicated in brackets behind the function names.0 .Ruth Schubert C-Course 20. then it should be defined with the void type! • <functionname>: the same rules apply for function names as for variable names. b). var_2. the keyword void is indicated in brackets behind the function. var_2). then the function call must be an indivicual instruction. If a function delivers no return value. /* float-cast float-Division */ return xyz. If a function delivers no value back. xyz = (float)p1 / p2. value2).

They can be called by any random program part. laim(). printf("behind Sendling\n").99 _______________________________________________________ Function definitions cannot be nested.03. laim(void). printf("before Laim\n"). sendling(). Functions can of course be called as nested. even if the source-programs can be found in different files. printf("behind Laim\n"). } void laim(void) { printf("in Laim\n").0 . Example  void sendling(void). void main(void) { printf("vor Sendling\n"). } Output: before Sendling in Sendling before Laim in Laim behind Laim behind Sendling Functions are usually global objects. _______________________________________________________ Version IT2. } void sendling(void) { printf("in Sendling\n").Ruth Schubert C-Course 20.

which delivers back a char-pointer). if the declared function is not defined within the same file. Example  extern float frechen( int argl. } _______________________________________________________ Version IT2.11..). var_2)..0 . . int).. calling and definition of a function float flo_func(int. the keyword external is given. the validity of a function can be limited to a file. double *arg2).. value = flo_func( var_1. the first argument is of int type. /* Function declaration */ void main(void) { .. The function prototypes of all standard functions are available in the includes. Example  extern char *cfunk(void).99 _______________________________________________________ By indicating static before the type-name respectively before the function name. an external function. an internal int-function with a constant char-pointer (string) as first parameter and a random number of the following parameters. Before the function type at a function declaration.Ruth Schubert C-Course 20.. The second argument is a pointer on double. The function name is not communicated to the linker in this case. Example  int xprintf(const char *format. 5. Example  Declaration.3 Function declaration Before it is called..03. The name of the corresponding include is indicated at the function description in the compiler handbook. /* Call */ . where the function is defined. a function is declared with number and type of parameters. which delivers back a float-value.. an external char-pointer-function without parameter (a function.

0 .03. } 5. A standardC-compiler can only perform a type test and automatic type adatption of the parameters. if necessary in another file */ float flo_func (int p1..4 Result transfer through the return value A function can return one(!) value to the calling program using the returninstruction. . This value is indicated in the return-instruction. void main(void) { . scanf("%s"... if the function was declared with a function prototype. hol_antw ()). int p2) { float value. return(response). The type indicated at the function definition must match with the type of the return value..11. } char *hol_antw(void) { printf("Please enter response (max " "20 characters: ").response). printf ("Response: %s ". } 5.Ruth Schubert C-Course 20.11.5 Parameter transfer The actual parameters of the function call should match regarding numbe rand type of formal parameters of the function definition. char * hol_antw(void). return(value). _______________________________________________________ Version IT2. Example  char resp[21]..99 _______________________________________________________ /* Function definition.

'e'. 5.5. input values can be transferred to the function or return values received from the function. field_2. char *p2. '2'.2 Function parameters as value ("call by value") Values are transferred to the function. '4'. '\0'}.11.03. char field 2[] = {'a'.11. 'b'.5. '3'.99 _______________________________________________________ For standard functions. the corresponding prototype include should be included for this reason.Ruth Schubert C-Course 20. '\0'}. 5.5. Through this address. the "exchange" function is called for this purpose. 5. if ( exchange(field_1. void main(void) { printf("%s \n". field_2). Fields can only be transferred through address parameters to the function.1 Type test of parameters under UNIX A type test of parameters enables however the syntax checker lint under UNIX.0 . The function can return no result through the "call by value" parameter. printf("%s \n". char field_1[] = {'1'. Parameters can be values ("call by value") or addresses ("call by reference"). 'd'. _______________________________________________________ Version IT2. which receives the start addresses of the fields and their length as parameters */ /* Function declaration: */ int exchange(char *p1. sizeof(field_1))) printf("Fields exchanged \n"). Example  /* The content of the fields "field_1" and "field_2" should be exchanged. int p3). 'c'.3 Function parameters as address ("call by reference") An address (pointer) is transferred to the function as a parameter. field_1).11. '5'.

i++) { between = *(adr1 + i). feld_2). /* Exchange ok */ Output 12345 abcde Fields exchanged abcde 12345 5. char *argv[]) or int main(int argc.Ruth Schubert C-Course 20.6 Argument transfer to the main-function A C-program can receive arguments transferred when calling. *(adr2 + i) = between. Syntax void main(int argc.11. } return(1). field_1). int number) { int i. char *argv[]) Description The argument transfer occurs through a parameter transfer to the main- _______________________________________________________ Version IT2.99 _______________________________________________________ else printf("Error \n").03. } int exchange (char *adr1. /* Exchange */ *(adr1 + i) = *(adr2 + i). i < number. /* no exchange possible */ for (i = 0. printf("%s \n".0 . char *adr2. printf("%s \n". if (number <= 0) return(0). char between.

0 . argv. The names argc and argv are however usual and should be kept. • argv: Pointer on a field of char-pointers. then it should deliver a return value back to the calling program (operating system). These pointers contain the start addresses of the argument string indicated at the program call. for (i=0. Tabs). The main-function can access the transferred data through the two parameters argc.i. If the main-function is of int type. These strings are character strings divided by separation characters (Blanks. } Program call ueb hello how are you Output _______________________________________________________ Version IT2. this function is the only function which can have none or two parameters. Example  For defining a main-function with argument transfer: Definition of the main-function /* File: ueb. which indicates the number of arguments in the command line. WIth these two parameters the main-function is always called. i< argc. Meaning of parameters of the main-function • argc: int-value. Thus.03. The formal parameters of the mainfunction can of course have random names. char *argv[]) { int i. these parameters were ignored.99 _______________________________________________________ function. In case of the present examples for the definition of the mainfunction.argv[i]).Ruth Schubert C-Course 20. i++) printf("\n Argument %d %s". then the return value is undefined.c */ void main( int argc. argc has thus at least the content 1. If the returnInstruction is missing. The program name is thus the first argument and is also counted by argc for this reason. The main-function can be of the type int or void.

on which the function pointer should indicate. value = atoi(string). Where • Rtyp is the type of return value of the function.11.1 Definition of a function pointer <Rtyp> (*<Fpointer>)(<ParFunc>). apart from that. Example  printf("Argument 1 + Argument 2 = %d \n". The address of a function can thus be given for example to another function as a parameter.99 _______________________________________________________ Argument 0 : ueb Argument 1: hello Argument 2 : how Argument 3 : are you It must be considered. that the transferred arguments are always in the character string. Should they be interpreted as numbers.7 Pointer on functions In C you can define pointers on functions. atoi(argv[1]) + atoi(argv[2])).Ruth Schubert C-Course 20. on which the function pointer should indicate • Fpointer is the name of the function pointer • ParFunc are the parameters of the function. _______________________________________________________ Version IT2.03. int value. char string[] = "1234". function tables can be realized. The parameter at atoi() is the start address of the string to be converted: the return value is the resulting int-value.0 . then the strings must be converted with the help of standard functions. 5. Example  for calling the standard function atoi. 5. corresponds: int value = 1234.11.7. The function atoi() converts a string into an int-value.

0 . which receives no parameters (void) and has a return value of char value.2 Assigning a function's address The address of a function is the function name without brackets.1])(). /* Def. defines a pointer.7.3 Calling the function through the function pointer char value = (*func_point)(). on a function named funcpoint. /* Call one of the two functions depending on the read-in number: */ (*func_poi[input . /* Declaration of functions */ func2(void). The address of this function is assigned to funcpoint like the following: funcpoint = char_func. Example  Assuming there's a function declared: char char_func(void). /* Assigning the function addresses To the pointer: */ func_poi[0] = func_1.h> void main(void) { int input.Ruth Schubert C-Course 20. func_poi[1] = func_2.99 _______________________________________________________ Example  char (*funcpoint)(void).&input). printf("Please enter function number [1/2] ").03. #include <stdio. 5.11. 5.7.11. Example  Calling functions through a function pointer field: void funcl(void). a field of function pointers: */ void (*func_poi[2])(void). scanf("%d". } _______________________________________________________ Version IT2.

• base points to the first element (0) of the array to be sorted. The comparison function compares the two elements (*elem1 and *elem2) and delivers an integer value as a result: *elem1 < *elem2: Return value < 0 *elem1 == *elem2: Return value = 0 *elem1 > *elem2: Return value > 0 For the comparison.03.h> void qsort(void *base. Analogical.Ruth Schubert C-Course 20. Description Sorts the elements of an array with the help of the Quicksort algorithm. qsort calls repeatedly the comparison function fcmp defined by the user for this purpose. • nelem contains the number of elements to be sorted.0 . the greater-than symbol (>) means. _______________________________________________________ Version IT2. } 5. Syntax #include <stdlib. • fcmp takes over the two arguments elem1 and elem2. the less-than symbol (<) means that the left positioned element should appear before the right positioned element when sorting. } void func_2(void) { printf("\n here is function 2 \n"). • width indicates the size of an individual element (in bytes). Return value None. size_t width. int (*fcmp)(const void *. that the element positioned on the left should appear after the element positioned on the right in the sorting. const void *)). Both are pointers to the elements of the array. size_t nelem.7.11.4 Sorting of fields with "qsort" A special use of function pointers is the use of the library function qsort.99 _______________________________________________________ void func_1(void) { printf("\n here is function 1 \n").

-646.03."wrelkjh".*(int *)b). } _______________________________________________________ Version IT2. 386436. 0. i< 5. "aKJHFUR".h> #include <string.9387.i_field[i]). sizeof(float). /* Output: */ printf("\nInt-Field sorted:\n"). /* Sortieren: */ qsort(i_field. for (i=0. i++) printf("%f\n".23876.h> #include <stdlib. float f_field[5] = {3. const void *b) { return strcmp((char *)a.15. 5.c_comp). 5.i_comp).c_feld[i]).11. else if (*(float *)a < *(float *)b) return -1. } int f_comp(const void *a.f_comp). sizeof(char[30]). for (i=0. i++) printf("%d\n". qsort(c_field."krewaj"}.Ruth Schubert C-Course 20. else return 0. for (i=0.h> int i_field[5] = {674. int i_comp(const void *a. } int c_comp(const void *a.3}. 5. } void main(void) { int i. printf("\nString-Field sorted:\n").-563}."lkiewrj".814. char c_field[5][30] = {"klsdjfh".(char *)b). sizeof(int). printf("\nFloat-Field sorted:\n"). qsort(f_field. i< 5. i< 5. const void *b) { if (*(float *)a > *(float *)b) return 1.f_field[i]). 47. const void *b) { return (*(int *)a .99 _______________________________________________________ Example  #include <stdio. i++) printf("%s\n".0 .97. -12.

} Example  Digit string of standard input to be read into a field The lowest value digit should be filed in the first field element. It must be considered that recursive functions require a lot of memory space and time.8 Recursive function call C-functions can be called recursively. if (until > 0) /* recursive function call: */ erg = bis * facul(until -1). } long facul(int until) { long erg.11. /* Declaration of function to calculate the faculty */ void main(void) { int number. else erg = 1.facul(number)). scanf("%d".0 . printf("\n %d! = %ld \n".number. applications which work with recursively defined data structures (for example tree structures) can be implemented more simple and comprehensible. The end of the recursion must be programmed carefully! Example  Calculating the faculty #include <stdio. field[2]= 9 _______________________________________________________ Version IT2. At each function call. &number). For example input: 903 field[0]= 3.99 _______________________________________________________ 5. this means that a function can call itself directly or indirectly. all local data are agreed and the memory place is allocated.03.h> long facul(int pl). printf("Faculty of: "). field[l]= 0.Ruth Schubert C-Course 20. return(erg). With the help of these functions.

/* Reversal of recursion at line end */ /* read-in character is filed on the "Return" of the recursion in 'feld': */ _______________________________________________________ Version IT2. /* Field index */ i=0.99 _______________________________________________________ #include <stdio. &i). which is used as field index. int *i).03. /* target field for the reversed digit sequence */ int i. /* "Over" the recursion */ if ((c=getchar()) == '\n') return. 1. int *i) { char c.h> #define MAX 10 /* maximum length of Digit string */ /* Function for recursive read-in of digits: */ void read(char *field. File read-in digits in opposite sequence starting with 'adr' => the last read-in digit is filed in the field[0l.0 .Ruth Schubert C-Course 20. void main(void) { char field[MAX]. Parameter: Start address of "char"-field 2. /* Read in digit sequence */ } /* read: Read in standard input digits. Parameter: Address of an "int"-variable. Interrupt at 'Return'. must containt the value 0 at the first 'read'Call */ void read(char *adr. read (field.

99 _______________________________________________________ read (adr.i). /* array of pointer to function returning pointer to float */ _______________________________________________________ Version IT2. /* Error: the first entered digits go lost.9 Complex definitions In case of complex data definitions. because there were more digits entered than maximum allowed */ *(adr+*i) = c.0 . /* Increase field index */ } 5. Example  float *(*ffunc[5])(). the following notions must be differentiated: <type> <name>[] <name> is an "Array of <type>" <type> *<name> <name> is a "Pointer to <type>" <type> <name>() <name> is a "Function returning <type>" Example  /* "clist" is an "array of (right before left) pointer to char": */ char *clist[3].03. /* read in next character */ /* "Return" of recursion: */ if (*i == MAX) return.Ruth Schubert C-Course 20.11. /* file the character read in on the "to-way" of the recursion in the field */ (*i)++.

by the position of the definition of indicating the control words static or register.12. Example  #include <stdio.1 Variable of the auto memory class Definition type: Validity range: Validity duration: Features: Definition of variables at the start of a block without indicating a memory class The block. then they have a random content. if it was defined with an initialization. The variable is assigned with its initial value at each block entry.Ruth Schubert C-Course 20.99 _______________________________________________________ 5. This value can be dynamic. Validity ranges can be: • a block • a function • all functionen in a file • entire programm Validity duration can be: · Program flow within a block · Program flow within a function · entire program flow For the examples up-to-now. If auto-variables are not initialized explicitly.0 . The memory class determines the validity range. auto-variables are applied at the stack.h> int func(void) { _______________________________________________________ Version IT2. The memory class of a variable is determined at definition. the validity duration and in some cases the initialization of a variable.03. where the variable was defined. if for example large fields or structures of the memory classe auto lead to a stack overflow. only variables of the auto Memory class were used. This must be considered. 5. where the variable was defined Program flow from entry until leaving the block. for example the result of a function.12 Memory classes Each variable is assigned to a certain memory class.

int. if it was defined with an initialization..0 . then the rest of the variables are applied as normal auto-variables.Ruth Schubert C-Course 20.99 _______________________________________________________ return 1.value). If in a block there are more registervariables defined than there are processor registers available.. } Output: value: 1 value: 2 value: 1 5. unsigned. */ } void main(void) { int value = func(). for example the result of a function. where the variable was defined. { int value = 2. Definition type: Validity range: Validity duration: Features: Definition of variables within a block and indicating the control word register before the type indication. printf("value: %d \n". The variable is assigned with its initial value at each block entry. They are filed.12. This value can be dynamic. The block where the variable was defined Program flow from entry until exiting the block. Only variables of the data type long. /* trivial function. printf("value: %d \n". The use of register-variables can shorten the program runtime in case of frequence accessing. as far as possible in the processor registers. } printf("value: %d \n". _______________________________________________________ Version IT2.value). value).03. char (integer number variables) can be defined with the memory class register.2 Variable of the memory class register register-variables are a special type of auto-variables.

The variable is allocated only once with its initial value. With this declaration. 5.99 _______________________________________________________ If register-variables are not initialized explicitly. For a variable there can only be one definition but as many declaration as desired.12. A variable must be either defined or declared before it is used. which were defined in another file. which were defined in another file. Block rules are valid for the declaration. If the declaration is outside any block limit. Validity range: global. also in functions. this means that the variable can only be used in the block where it was declared. which are defined in the file. thus they get a fixed memory space assigned (as opposed to the auto-variables on the stack). The external-declaration To access the variables. the compiler is communicated the type of these global variables and there is an external-marker entered on the variable for the linker.0 . then they are pre-allocated with zero. If global variables are not initialized explicitly. in each function. which can be filed in the data range 5. then the variable is valid in all functions. Validity duration: Total program runtime Features: Global variables are filed in the program data range.1 Global variables and the external-declaration Type of definition: Definition outside any block limit (also function block) without indicating a memory class. _______________________________________________________ Version IT2.3 Variables. This only requires an external-declaration.03.Ruth Schubert C-Course 20. then they have a random content. register char c. Example  register int x. this variable must be communicated with an external-declaration.3. The variable name is communicated to the linker. The initial value must be a constant expression. at program start should it be defined with an initialization. This way functions which are defined in other files can access the variable.12.

12. Validity range: In the block. int main(void) { . .0 . } 5.2 static-variables Type of definition: Within a block or outside any block by showing the keyword static.3. glob_var = 1. which were defined outside the block _______________________________________________________ Version IT2. func_x(). .. where the variable was defined respectively in all functions of the file.. glob_var)...99 _______________________________________________________ Example  /* File: main.. Validity duration: Total program runtime Features: • static-variables. printf ("glob_var: %d \n". } /* File func..Ruth Schubert C-Course 20. /* Declaration of a function: */ extern void func_x(void).. if the variable was defined outside any block limit..03.c */ /* Definition of global variables: */ int glob_var. void func_x(void) { .c */ /* Declaration of variables: */ extern int glob_var.

03. Thus it should be worked according to the rule. Example  /* The program reads in from the user a 4-digit secret number. functions can be developed with "memory". Because static-variables are valid during the entire program runtime.0 .&input). _______________________________________________________ Version IT2. after 3 faulty inputs. differ from global variables only by the fact.) { printf("please 4-digit secret number " "enter").99 _______________________________________________________ limits. Functions which were defined in other files cannot access staticvariables. that there should be as little data as possible generally available. static-variables are only allocated with their initial value once at program start. the function 'alarm' is called */ #define TRUE (1==1) #define FALSE (O==1) #include <stdio. which were defined within a block limit ' differ from the auto-variables by the validity duration. scanf("%4d". /* Function for read-in and testing of the secret number */ void main(void) { int i. static'-variables.. if (secret()) { all ok().h> static int input. In case of successful entry. /* for entering the secret number */ int secret(void). The initial value must be a constant routine. break.Ruth Schubert C-Course 20. that the variable name is hidden before the linker. the function 'all_ok' is called. The user has 3 trials to enter the correct secret number. for(.

/* Secret number: */ int secret_nr = 1234. if (input == secret_nr) { secret_count = 0. } else { if (++secret_count >= 3) { alarm (). } return(FALSE).Ruth Schubert C-Course 20.0 . secret_count = 0.99 _______________________________________________________ } } } int secret(void) { /* The next variable counts how many times 'secret' was called in a comparison cycle */ static int secret_count = 0. } } _______________________________________________________ Version IT2. return(TRUE).03.

13 Dynamic memory management For program variables there are the following filing possibilities in the memory: Variable types local variables static.. global variables Dynamic variables Memory Stack. there is the possibility of dynamic memory request. register Data range of program Dynamic memory (heap) Assignment of. until the program end or until the explicit release by the program. · ROM-data: data.Ruth Schubert C-Course 20. that the transferred string is not modified: */ int funk (const char *message). In order not to request the maximum necessary memory space for the program each time.. Compiler Compiler Compiler or operating system The number and size of the necessary memory space ranges is often unknown at the moment of programming. · partly write-protected data in shared-memory-systems. that this variable cannot be modified.03. that a transferred parameter is not allowed to be modified in the function.4 Data type indentifier const Using the const keyword before a variable definition it is agreed. The variables which are filed in the dynamic memory are valid independento of the block structure. The available dynamic memory range is also called "heap". Example  const int var1 = 100.99 _______________________________________________________ 5. Only valid for pointer transfer ! (Callby-reference).12. the additionally needed memory is requested (or allocated) from the operating system during runtime. which cannot be modified physically (like for example the content of an EPROM).0 . This way. (Error message: no lvalue or lvalue required) Use · Declaration of function parameters: agreement. /* The next function declaration determines. _______________________________________________________ Version IT2. Thus it cannot be positioned on the left of an assignment character. 5.

Return value calloc returns a pointer to the newly allocated block.Ruth Schubert C-Course 20.03. it must normally be recasted to the desired data. /* Copy "Hello" in this memory block: */ strcpy(str. The entire block is set to 0. Description calloc allows access to the C Heap. The heap is available for dynamic allocation of memory blocks of variable size. /* Allocated memory for 10 chars: */ str = (char *) calloc(10. If there is not enough memory space available or either nitems or size equal zero. /* Show string at: */ printf("String is %s\n". Example  #include <stdio. /* Release memory again: */ free(str). Many data structures like trees and lists use memory allocation on the heap. sizeof(char)). then calloc returns ZERO. 5.h> #include <stdlib. str).h> #include <string.13. size_t size). } _______________________________________________________ Version IT2.99 _______________________________________________________ The functions described in the following paragraphs are available for managing the dynamic memory. calloc allocates a block of the size nitems * size. Because the returned pointer is of type void *.h> void main(void) { char *str = ZERO.h> void *calloc(size_t nitems.1 calloc Syntax #include <stdlib.0 . "Hello").

then malloc returns ZERO.2 malloc Syntax #include <stdlib.h> void *realloc(void *block. then the memory space is released and ZERO is returned.Ruth Schubert C-Course 20. except for the following: • Only the number of necessary bytes is transferred in the size parameter.13. Description realloc tries to increase of diminish a previously allocated memory block to size Bytes.. • The memory is not initialized with zeros Due to these reasons malloc usually works faster than calloc. _______________________________________________________ Version IT2.99 _______________________________________________________ 5. Description malloc works like calloc. Example  float *ffield. If there is not enough memory space available or size equals zero. If size is zero. .h> void *malloc(size_t size).3 realloc Syntax #include <stdlib. The block parameter points to a memory block previously allocated with calloc. size_t size).03. Return value malloc returns a pointer to the newly allocated block.. malloc or realloc.13. Because the returned pointer is of void * type. it must usually be recasted to the desired data type. /* A float-field of the size 'fnumber' is applied: */ ffield = (float *)malloc(fnumber * sizeof(float)).0 . 5.

. realloc modifies the size to the allocated memory block to size.13. Description free releases a memory block again. If the memory block cannot be reallocated. one that was allocated by calloc. /* A long-field of the 'lnr' size is allocated: */ lo = ((long *)malloc(lnr * sizeof(long)). then the memory block is released and realloc returns ZERO. Example  char *buffer.. then ZERO is returned. _______________________________________________________ Version IT2. Example  long *lo. .4 free Syntax #include <stdlib. 5. Thus it is again available for further reservations. Return value realloc returns a pointer to the reallocated memory block. Return value None.. malloc or realloc through a previous call. n_lnr * sizeof(long)).Ruth Schubert C-Course 20. as far as necessary. If size equals zero.03. by copyind the content into a new memory block.. which differs from the pointer on the initial block.99 _______________________________________________________ If block equals ZERO.. /* A larger field is necessary (new size: n_lnr): */ lo = (long *)realloc(lo. then realloc works just like malloc.h> void free(void *block). . .0 ..

2 Declaration of s structure type Example  struct appointment { int year. 5.product is the start address of this field. the structure contains the int-variables vehicle.14. vehicle. _______________________________________________________ Version IT2.0 . } vehicle. 5.Ruth Schubert C-Course 20. The vehicle structure is defined and thus also the memory space allocated. as well as the floatvariable vehicle.price. float price..capacity. Unions (see "Unions (Variants)" on page 174) Pointer on structure of the same structure type (see "Definition of a recursive structure" on page 150) Structure fields (see "Definition of a structure field" on page 125) can be defined. 5.99 _______________________________________________________ /* A char-field is applied for 'c_size' characters: */ buffer = (char *)malloc(c_size * sizeof(char)). This structure contains a char-field. /* The char-field is not necessary anymore: */ free(buffer). Apart from that. ..1 Definition of a structure Example  struct { char product[20]. The elements of a structure could be: Variables of the basic data types (see "data types" on page 31) Pointer (Pointer) (see "Pointer (Pointer)" on page 82) Fields (Arrays) (see "Fields (Arrays)" on page 79) other structures. int performance.14. bit fields (see "Bit fields" on page 172).14 Simple structures A structure comprises variables of different data types.03. int capacity.performance and vehicle.

int hour. 5.99 _______________________________________________________ char month[10]. A structure type appointment is agreed.3 Definition of a structure and simultaneous declaration of the structure type Example  struct broadcast { char title[40]. struct appointment start. } news.start. This structure contains the elements: news.03..14. int minute.start.0 . The structure news is defined.minute Additionally.4 Accessing structure elements _______________________________________________________ Version IT2. news. news. struct appointment end.title..end.Ruth Schubert C-Course 20. }. the structure type of the broadcast name is given. No structure is defined! No memory space is allocated! Structures can be defined with the help of structure types. int day. 5.14. news.year.month .

.4. prac->hout = 12. which is addressed through a pointer can be accessed with the arrow operator. Example  int func_x(struct appointment *prac) { ..5 Definition of a structure field Structure fields are used. prac->minute = 10.Ruth Schubert C-Course 20.hour = 12.14. with the help of the "*"-operators (not usual).minute = 10.99 _______________________________________________________ 5. we must set here the following advantages and disadvantages of structure fields: _______________________________________________________ Version IT2. "September").month. Example  Struct appointment practice. (*prac). "September"). strcpy ((*prac). strcpy(prac->month.4. Example  (*prac)... } The elements of a structure addressed through a pointer can be accessed also as usual. .operator The elements of a structure.operator Individual structure elements are accessed with the point operator.' . Because we will learn later about other organisation types (see "Optimized organisation of same type structures" on page 149). 5.03.hour = 12.0 .minute = 10. 5.2 The '->' . if several same type structures should be managed and handled together in a program. like other fields. practice.1 The '.14. practice.14.

· Sorting of structure fields is slow. {30.6 Initialization of structures Structures are initialized with the same rules as fields. but the insertion or deletion of individual elements is slow and complicated. "squid".03.14. Example  struct broadcast program[20]. } article = {10.99 _______________________________________________________ Advantages of structure fields · Fast access to elements of structure fields is possible. · Structure fields contain no overhead to form organisation. Disadvantages of structure fields · Structure fields of variable size can be realized through dynamic memory management (see "Dynamic memory management" on page 118). Example of a Structure element: program[ 3].start.hour */ 5. · Insertion or deletion of individual elements of a structure field and keeping a sorting is only possible through time consuming copying. float price[2]. 2. the initial values are indicated in accolades after the definition Example  struct art { int number. Successful test  _______________________________________________________ Version IT2.5}}. because the entire contents of the structure field elements must be copied again.0 . float weight. char *name. which contains 20 Structures of the type 'broadcast'. 67. as far as the index is sufficient as a selection criteria for the structure field element to be addressed.25. /* a field is defined .Ruth Schubert C-Course 20.

(poi++)->str. 2. void main(void) { struct nixfix abc [] = { {"aaa". for (i=0. ++(poi->nr)). abc+1}. struct nixfix *poi.str). poi = poi->spoi. }. abc[1]. int i.Ruth Schubert C-Course 20.str. poi= abc.spoi->str). abc[1]. (poi--)->str. int nr. abc } }. 3. abc[2]. i< 6.99 _______________________________________________________ What does the following program display? struct nixfix { char *str. struct nixfix *spoi. abc+2}.0 . printf(" %s %s %s \n". printf("\n %s %s %s \n". } Solution: aaa aaa aaa bbb bbb ccc 2 3 4 3 4 5 _______________________________________________________ Version IT2. abc[0]. } printf("\n"). 1.03. {"bbb". i++) { printf(" %d". {"ccc".spoi->str.

h> #include <stdlib. typedef is entered to: · improve the readability of programs (a complicated data type Is hidden behind an easy to understand name) · improve the portability of programs (a system dependent data type can be "exchanged" at a central location) Example  typedef char *string.h. int age.03.h> void main(void) { time_t t. The belonging typedef-instruction is located in the standardinclude time.h). */ string lines[LINES]. person headcount[P_NUMBER].0 . /* The next definition corresponds to: char *lines[LINES]. } person. No new data type is defined! typedef is often introduced by standard functions. _______________________________________________________ Version IT2. #include <stdio.99 _______________________________________________________ 5. A synonym for an already existing data type is created. Example  typedef struct { char name[20]. The corresponding typedef instructions are then available in standard-includes (mostly in stdlib.Ruth Schubert C-Course 20.15 typedef Some type names can be introduced with the help of the typedef keyword. The representation of time instruction is hidden behind the type name time_t. float salary.h or stddef.h> #include <time. Example  In the following example the current time is determined and displayed on standard output.

west = 270 } _______________________________________________________ Version IT2. else printf(ctime(&t)).Ruth Schubert C-Course 20. south = 180. yellow or red.99 _______________________________________________________ if (-1 == time(&t)) /* acquire current time */ error(TIME). This standard value assignment can be varied: Example  enum direction { north = 0. Example  enum stoplight { green. Example  enum stoplight a_road1. This defines a new data type stoplight. The countup values are assigned increasing values starting with 0. red }. yellow the value of 1 and red the value 2.0 . When defining such a data type. but no arithmetic operations. the value range is defined by listing all possible elements. Hot tip  It is recommended to used only comparison operator and instructions for enum type variables. this way. /* prepare time instruction and display */ } 5.03. east = 90. yellow. a_road1 = red. in the above example green gets the value of 0.16 enum Enumeration data types can be defined using the enum keyword. Variables of this data type are allowed only to accept the indicated values green.

there are functions of the C-standard library used.1 List of FILE file access functions (incomplete) Name fopen freopen fclose fflush getc. Advantages: · portable programming · efficient file access through buffered reading / writing. 5.17 File accesses through the FILE-structure For the file access. The FILE-structure is defined in the standard-include <stdio. By reducing a disk access. Data blocks are not taken individually from the disk or written on it but buffered in their "normal size" (for example 512 Byte sector length) in the memory. The FILE-structure is applied when opening the file. These functions access the files buffered. it contains information.0 . then this include must be also incorporated. with the help of the FILE-structure.h> through a typedef instruction.17. 5. the file access times can be reduced considerably.Ruth Schubert C-Course 20.99 _______________________________________________________ orientation.03. fgetc putc. If a program uses the file access functions of the C standard library. which is necessary for the buffered writing / reading of the file. fputc fgets fputs fscanf fprintf fread fwrite fseek See page 131 133 134 134 135 136 140 141 141 142 143 142 145 Function Opening a file Closing a file Character by character input Character by character output String by string input String by string output Formatted input Formatted output Block by block input Block by block output Help functions for random access (Random _______________________________________________________ Version IT2.

r+ Open an existing file for revision (simultaneous reading and writing).2 fopen – opens a file Syntax #include <stdio. then this file is overwritten.0 .h> FILE *fopen(const char *filename. const char *mode). then the same as in w is performed. They can be used through the FILE-pointer with the following symbolic name (without previous fopen!): stdin stdout stderr for standard input for standard output for standard error output In the string mode the type of file opening is determined: r Open file for reading (read) w Open file for writing (write). a File for appending (append) opened at file end. The number of open files is limited. Three FILE objects are automatically generated at program start. which is used to create a reference for this file in the following file operations. if a file with _______________________________________________________ Version IT2.99 _______________________________________________________ ftell rewind feof 147 147 148 Access) File end recognition 5. w+ Open a new file for revision (simultaneous reading and writing). fopen returns a pointer. If a file with this file name already exists.Ruth Schubert C-Course 20. if the file does not exist.17.03. which is defined by the file name filename and allocates a FILE structure to it. Description Opens a file.

Ruth Schubert C-Course 20. fp = fopen("example."wb+"). *wfile. if a generation or opening of a file is desired in the binary mode10. in case of error.dat". · an output cannot occur immediately after an input. 9 Textmode: In the text mode. the character string CR (Carriage Return) and LF (Line Feed) is translated in a single LF during read-in. it must be considered. a b must be appended.0 . If the file is named _______________________________________________________ Version IT2. Return value In case of successful execution.as well as output operations can be performed on it. then a t must be appended at the mode string (for example rt or w+t etc.1 Particularity when indicating the file name in case of BORLAND-C Attention  If a path should be indicated in the filename filename.17. an individual LF is converted in a sequence CR / LF. but · an input cannot occur immediately after an output. In case of output. that the path separator \ should be indicated double. wfile = fopen(tmpdat[i]. without fseek or rewind being called at least once in the meantime or the input has reached End-offile. a+ Open a file for revision (simultaneous reading and writing) at the file end (append) respectively. fopen returns a pointer to the FILE-structure assigned to the newly opened file. all characters are read in or displayed without translation. 5.03.2. Example  FILE *fp. generate it. the zero pointer ZERO is returned. If a file is opened for revision then input. without fseek or rewind being called at least once in the meantime."r+").99 _______________________________________________________ this name already exists.) The same way. 10 In binary mode. then it is deleted. If it is to be indicated that a file should be generated or opened in the textmode9. if it does not exist.

Example  /* The standard output is diverted to the "new. then it was not successful.17. Description Because the number of opened files is limited and rest data can go lost in case of sudden interrupt (see "fflush – empties the buffer" on page 134) files should be closed using the fclose-instruction. then the following string must be indicated: \\user\\dir\\xyz.4 fclose – closes a file Syntax #include <stdio. if it is EOF. const char *mode.dat". as soon as they are not used anymore.0 . stdout).h> FILE *freopen( const char *filename. Return value If the return value is 0.3 freopen – allocates new file to buffer Syntax #include <stdio. FILE *stream). 5. freopen is mainly used to divert stdin. _______________________________________________________ Version IT2. then the function was successful.17. allocates its FILE-structure for a new file and opens this new file. Description Closes an already opened file. stdout or stderr to a file during the program flow.99 _______________________________________________________ \user\dir\xyz.dat 5.Ruth Schubert C-Course 20.03.dat" file: */ fp = freopen("new."w". Bei normalem Programmende erfolgt ein automatisches Schließen aller Dateien.dat.h> int fclose(FILE *stream).

The data buffer is usually written on the disk first. then it was not successful.5 fflush – empties the buffer Syntax #include <stdio. because the overhead of a function call drops.6 Character by character reading and writing Character by character reading and writing are implemented by one function each and an equivalent macro.0 . 5.17. (Only for files. 5. instead of the call.03. If the protocol file of a program should always contain the most up-to-date protocol status. · If memory space is short. then the data buffer must be ensured through the fflush-command. That a use can read out for example the newest data while the program is still running.99 _______________________________________________________ Example  ret = fclose(fp). This function can be used for example in the following cases: If after a write command it must be avoided at any cost. _______________________________________________________ Version IT2. because Then the entire implementation of the compiler is not filed at each call. then the macro should be used. Description It writes the data buffer on the disk. which were opened for writing). Example  ret = fflush(fp).17. fflush must be called after each protocol entry. that the data buffer goes lost through a faulty program end.h> int fflush(FILE *stream). then the function should be used.Ruth Schubert C-Course 20. then the function was successful. if it is full or if the file is closed. if the return value is EOF. The programmer should use either the macro or the function according to the following points of view: · If a fast resolution is emphasized. Return value If the return value equals 0.

17.2 Character by character writing Syntax #include <stdio.h> int fgetc(FILE *stream).03.1 Character by character reading Syntax #include <stdio.6. FILE *stream). /* Function */ or int putc(int c.h> int fputc(int c.6. /* Macro */ Description fputc or putc write the character c in the file named by stream.h> void main(void) { char ch.99 _______________________________________________________ 5. /* Function */ or int getc(FILE *stream).0 . Rückgabewert Im Fehlerfall oder wenn das Dateiende erreicht ist. _______________________________________________________ Version IT2.17. Beispiel  #include <stdio. ch). } 5. wird als Rückgabewert EOF zurückgeliefert. printf("Enter a character:").Ruth Schubert C-Course 20. ch = getc(stdin). printf("The character was: '%c'\n". /* Macro */ Description fgetc or getc read a character from the file. which is named by the FILE Pointer stream and delivers this character in the return value. FILE *stream).

99 _______________________________________________________ Return value In case of error. /* File (1.stdout) Example  /* The program reads a file character by character and displays these characters on standard display. FILE *fp.3 The macros getchar / putchar If inputs are read by stdin or outputs should be written on stdout. char *argv[]) { int character. } } 5.h> void main(void) { char msg[] = "Hello world". Example  #include <stdio.6. The file name is transferred as a first argument at program call */ #include <stdio. while (msg[i]) { fputc(msg[i].h> void main(int argc.Ruth Schubert C-Course 20.03. Argument) open for reading: */ _______________________________________________________ Version IT2. int i = 0.0 .17. EOF is delivered as a return value. stdout). then the following macros could be used for simplification: #define getchar(void) getc(stdin) #define putchar(x) putc(x. i++.

h> int ungetc(int c.. exit(1)..99 _______________________________________________________ if ((fp= fopen(argv[1].*/ . "r")) == NULL) { printf ("%s cannot be " "opened\n". Example  /* In the 'GOODS' file there are product names and Article numbers filed in a sequence.argv[1]). c is not allowed to be EOF! Return value The function delivers back c or EOF. ungetc is not allowed to be called twice in a row. FILE *stream).Ruth Schubert C-Course 20.03. The program fills the data in the structure field 'article' Example for the content of the 'GOODS' file: Butter786458763sausage78346567cheese765marmalade897..17. Thus only a character can be reset in a file. Description ungetc resets the character c back to the file characterized by stream. _______________________________________________________ Version IT2.6. } 5.0 . } /* Display file until file end on standard output: */ while((character = getc(fp)) != EOF) putchar(character)..4 Resetting characters Syntax #include <stdio.

int nai. } while ((char != EOF) && isalpha(char)). if ((char!= EOF) && isdigit(char)) /* Reset digit: */ ungetc(char. } while ((char != EOF) && isdigit(char)). if (isalpha(char)) article[wi]. goods = fopen("GOODS".Ruth Schubert C-Course 20. do { /* read article name: */ nai = 0. } article[100]. _______________________________________________________ Version IT2.99 _______________________________________________________ struct { char name[30].."r"). FILE *goods. do { char = getc(goods). do { char = getc(goods).0 . . int wi = 0. /* Article name */ /* Article number */ /* Index in the article field */ /* Character index within an article name */ /* Character index within an article number */ int nri.03.. goods). char nr[20].name[nai++]= char. .. if (isdigit(char)) article[wi]..nr[nri++] = char. /* Read article number: */ nri = 0.

msg). wi++. char msg[20]. /* Read string from file:*/ fgets(msg. 5. "r").7.0 .FIL". } while (char != EOF). . goods). Example  #include <stdio.99 _______________________________________________________ if ((char != EOF) && isalpha(char)) /* Reset letter: */ ungetc(char. /* Display string: */ printf("%s".03. which is characterized by stream. _______________________________________________________ Version IT2.7 Reading and writing strings 5. stream). Description fgets reads from the file. Return value In case of error or EOF the return value is ZERO.17. int n.. either one strings (string until \n inclusive) or until EOF or n-1 character after s.Ruth Schubert C-Course 20. /* Open file for reading: */ stream = fopen("DUMMY. The string is finalized with \0. sizeof(msg).h> char *fgets(char *s.17.h> void main(void) { FILE *stream. usually s is returned.1 Reading strings Syntax #include <stdio.. FILE *stream).

Description: fputs writes the character string starting with s until \0 exclusively. const char *format[.h> int fscanf(FILE * stream.1 Formatted reading Syntax #include <stdio. .99 _______________________________________________________ fclose(stream). which is characterized by stream.Ruth Schubert C-Course 20..17.h> void main(void) { /* Write a string on standard output: */ fputs("Hello world\n". Return value: In case of error EOF is returned.]).2 Write string Syntax #include <stdio. address.8 Formatted reading and writing 5. Example  #include <stdio. not-negative number value.03. FILE *stream). otherwise a random. _______________________________________________________ Version IT2. } 5.h> int fputs(const char *s. in the file.7.. stdout).0 .8.17. } 5.17.

"%s %s %d.)) _______________________________________________________ Version IT2. &persnr.h> int fprintf (FILE *stream. argument.. /* Buffer for return value of "fscanf" */ source = fopen("source. first name. name.8. &year. Return value The number of successfully read-in elements EOF or 0 (error detection).34 19389. . int sretc. "w+"). street.. modifies them according to the formats into format and stores them in the arguments at address etc.dat"..2.. target = fopen("target. Description fprintf writes into the stream file. .98 667890 Donaustr. &housenr. &day.2 Formatted writing Syntax #include <stdio. "r").%d. A sentence of the source file: Huber Friedrich 1. &yincome.98 */ . const char *format[.. &month.03.. while ((sretc = fscanf(source.1934 19389. *target.Ruth Schubert C-Course 20.]).%d %f %ld %s%d". The format rules are the same as for scanf (see "Input with scanf" on page 45). 5. FILE *source.17.99 _______________________________________________________ Description fscanf reads from the stream file characters. Function like printf (see "Output with printf" on page 40) Example  /* The program excerpt formats a file into another one.3 According sentence of target file: 667890 Friedrich Huber 01.0 .dat".02.

19%02d%10. size_t n. If the return value equals n.17. int house number. day. int day.h> size_t fread(void *ptr. first name.0 .1 Reading block by block Syntax #include <stdio. if 0 is returned then an error or EOF has appeared. char street[MAX_STREET]. month. after ptr. Return value Number of actually read elements. persnr. name.2f\n".99 _______________________________________________________ == 9 ) { fprintf(target. /* Reads 5 units _______________________________________________________ Version IT2.fp). then all desired data could be read. float jincome.9 Reading and writing block by block 5. FILE *stream). How must the variables be defined? char name[MAX_NAME]. year.17..10. 5. size_t size.03. month.Ruth Schubert C-Course 20. year. char first name[MAX_FIRST_NAME]. Description fread reads n-times size bytes from the file characterized by stream.9. "%-10ld%-12s%-15s%02d. long persnr. jincome). } .5. Example  anz = fread(buf.%02d..

i = 0. void main(void) { FILE *stream. char ch.fp). size_t n.2 Writing block by block Syntax #include <stdio. size_t size. then the function was successful.03. in all other cases an error has occurred.99 _______________________________________________________ for each 10 bytes "fp" after "buf" */ Example  anz = fread ( buf.Ruth Schubert C-Course 20.1. struct mystruct s. FILE *stream). sizeof(s). fwrite(&s.h> struct mystruct { int i.0 . _______________________________________________________ Version IT2. stream = fopen("TEST. Example  #include <stdio. which is characterized by stream. s. "wb").h> size_t fwrite(const void *ptr.LST". }. Description fwrite writes n-times size bytes from ptr into the file.sizeof(buf).ch = 'A'. /* Reads as many characters as there can fit into "buf" from "fp" tp "buf" */ 5.17. s.9. Return value If the return value coincides with n.

/* write structure "s" into the file */ fclose(stream). To create more complex files.03. Description fseek shifts the read / write pointer of the stream file by the number of bytes indicated in offset. this means that after opening. int whence).17.h: Constant SEEK_SET SEEK_CUR SEEK_END Return value fseek returns 0.17. 5. stream).0 . if an error has occurred.1 fseek – Positioning of the write / read pointer Syntax #include <stdio.h> int fseek(FILE *stream. Thus an offset higher than 0 means a shifting to the file end and smaller than 0 a shifting to the file start. /* close file */ } 5.10. Example  Numeric value 0 1 2 Meaning Shifting from file start Shifting from current position Shifting from file end _______________________________________________________ Version IT2. a file was continuously read / written from the start to the end. the corresponding constants are defined in stdio. the help functions described in the following are available for random access. long offset. The parameter whence indicates from which reference point the shifting should be made. if the write / read pointer could be shifted successfully and another random value.10 Functions for random file accessing The functions named up to now have been for sequential data access.Ruth Schubert C-Course 20.99 _______________________________________________________ 1.

b_number. argument A block should consist of 5 characters.(atol(argv[3])-1) * B_SIZE. char buf[B_SIZE].03. argument n: 3. 0). i++) { fread(buf.17. argument z: 4. i< b_number. int i. char *argv[]) { FILE *fp1. */ #include <stdio.h> #define B_SIZE 5 void main(int argc. fwrite(buf. fp1). No error handlings occur. B_SIZE.Ruth Schubert C-Course 20.2 ftell – Indicating the position of the write / read pointer Syntax #include <stdio. for (i = 0. fseek(fp1.10. argument file_2: 2. *fp2. b_number = atoi(argv[4]).0 . _______________________________________________________ Version IT2. Command lines arguments: file_l: 1. B_SIZE. fp2) . } } 5."w").h> long int ftell(FILE *stream). fp1 = fopen(argv[1]. 1."r"). fp2 = fopen(argv[2].99 _______________________________________________________ /* The program reads from "file_1" starting with the n block z blocks and writes them in "file_2". 1.

h> int feof(FILE *stream).0 . Successful test  What does the following program display? #include <stdio.3 rewind – Resetting the write / read pointer Syntax #include <stdio.10. otherwise a value unequal 0.Ruth Schubert C-Course 20. Return value Returns 0. Description feof checks.11 feof – Detecting the file end Syntax #include <stdio. if the file end was not yet reached.99 _______________________________________________________ Description ftell delivers the number of bytes. 5.03. Description rewind sets the read / write pointer of a file stream on the file start and thus deletes the EOF-characteristic and the error detection.h> void rewind(FILE *stream).17. whether the file end was reached through a previous reading of the file end.17. by which the read / write pointer is distanced from the stream file start.h> #define STRING_SIZE 34 _______________________________________________________ Version IT2. 5.

99 _______________________________________________________ void main(void) { FILE *fp. _______________________________________________________ Version IT2.18 Optimized organisation of same type structures Until now. fp = fopen("example". fp = fopen("example".-((long) STRING_SIZE * 3). same type structures.03. This method is not always the best one (see "Definition of a structure field" on page 125). c_var). while(fgets(buf. which do not present the disadvantages of structure fields. char buf[100]. i_var. char c_var = 'A'. zz++. } fclose(fp). int i_var = 2.Ruth Schubert C-Course 20. "r"). 2).buf). } Solution: String: 8 i_var: 16 c_var: H String: 9 i_var: 18 c_var: I String: 10 i_var: 20 c_var: J 5. for (i = 0. i++) { fprintf(fp. i < 10. int i. i_var += 2. fp) != ZERO) printf("%s". c_var++. fseek(fp."string: %2d i_var: %2d " "c_var: %c\n". are always applied in structure fields. which should be managed and handled together in a program. int zz = 1."w").0 . In this paragraph we get acquainted with alternative organisation types for same type structures.100.

18. } disk_management. #pragma extref _floatconvert 5.0 . the access to such organized structures can be accelerated by using hashing (see page 163).03.Ruth Schubert C-Course 20. The memory space for each structure within this linked list is allocated individually.3 Linked lists A linked list is an organisation of same type structures. Thus the following features result: Advantages of linked lists · The memory space necessity for the structures can be adapted exactly to the actual needs during runtime.2 Definition of a recursive structure We can talk about a recursive structure. struct management *front_poi. where the individual structures contain at least one pointer.1.1 Due to a problem with the linker in BORLAND-C 3. the following two strings must be added at the beginning of each example porgram of this chapter: extern void _floatconvert(). char dat_name[l4].18.1 Note for examples when using BORLAND-C 3. if the pointer structure contains structures of the same structure type. which indicates to the next structure within a desired sorting of individual structures. _______________________________________________________ Version IT2.99 _______________________________________________________ Thus it is the case of · Linked lists (see "Linked lists" on page 150) · Binary trees (see "Binary trees" on page 163) Further on. 5. Linked lists and binary trees operate with recursive structures. Example  struct management { struct management *back_poi. which are discussed in the following paragraph.18. · Introduction and removal of individual structures while keeping a sorting of structures is possible without re-copying of structures. 5.

Ruth Schubert C-Course 20. /* Global pointer on structure for the anchor of linked list: */ student *anchor=ZERO.3. then the anchor points to ZERO. float c_note. 5. which indicates to the first element of the list. A simple forward linked list is especially suitable for lists. which indicates to the next element of the list.03. • The last element then contains a pointer.99 _______________________________________________________ Disadvantages of linked lists · Access to individual structures is possible only sequential and thus slower. /* builds from a file a simply linked list */ void list(void). }schueler. thus to indicate the end of the list. This element was first read in when the list was made.0 . /* displays the simple linked list */ void main(void) _______________________________________________________ Version IT2.h> /* Structure declaration: */ typedef struct person { char name[30]. • Each list element contains a pointer. which shows ZERO.h> #include <stdlib. which is designated as an anchor. int age. If the list is empty. Example  #include <stdio. where the access structure to the list elements should occur in the same sequence as the structure. struct person *next.1 Simple forward linked list The simple forward linked list is characterized by the following: · There is a pointer.18. /* Function declarations: */ void linkstruct(void).

student *hp1. exit(-2). "r")) == ZERO) { printf("File cannot be opened" "for reading\n"). &hp1->c_note)) { /* Link. exit(-1). hp1->name.99 _______________________________________________________ { linkstruct().dat". if ((fp = fopen("student. /* Linked list display */ } /* Open a fixed preset file for reading and read out Data set by data set in structures. the structures should be linked to a simple linked.Ruth Schubert C-Course 20. *hp2.0 . &hp1->age. } while (!feof(fp)) { if ((hp1 = (student *) malloc(sizeof(student))) == ZERO) { printf("Not enough memory" "available\n").03. } if (3 == fscanf(fp. "%s %d %f". /* Function call Build string */ list(). where the first read in data set becomes the start of the linked list */ void linkstruct(void) { FILE * fp. so that the element which was read in first is the anchor of the linked list: */ if (anchor == ZERO) { /* It is the first element which should be _______________________________________________________ Version IT2.

which indicates to the last element of the list. thus to mark the beginning of the list. for (hp = anchor.0 . } else { /* It is not the first element.3. } 5. • Each list element contains a pointer. which indicates to the previous element of the list. hp = hp->next) printf("Name: %s Age: %2d C-Note: %. hp->name.2 Simple backwards linked list The simple. which is marked as an anchor. hp->c_note). _______________________________________________________ Version IT2. hp->age. then the anchor points to ZERO. } } fclose(fp). If the list is empty.03. • The first element then contains a pointer. this is why an anchor must be set */ anchor = hp1. This element was read in last when the list was structured. hp != ZERO.99 _______________________________________________________ read in.Ruth Schubert C-Course 20. hp2 = hp1. so set the next-pointer of the previous one to the current data set */ hp2->next = hp1. } hp1->next = ZERO.2f\n".18. backwards linked list is characterized by the following: • There is a pointer. } /* Output of simple linked list: */ void list(void) { student *hp. which indicates ZERO.

03.Ruth Schubert C-Course 20. /* Display linked list */ } /* Open a fixed preset file for reading and read out data set for data set in structures. }student. for which the structure of access to the list elements may also occur in a backward structure sequence – for this type of linked list. /* displays the simple linked list */ void main(void) { linkstruct(). Link the structures to a simple linked list. /* Function declarations: */ void linkstruct(void).99 _______________________________________________________ A simple backwards linked list is especially suitable for lists.h> /* Structure declaration: */ typedef struct person { char name[30]. Example  #include <stdio.h> #include <stdlib. /* Global pointer on structure for the anchor of the linked list: */ student *anchor = ZERO. the structure is very simple. struct person *prev. /* Function call Build link */ list(). _______________________________________________________ Version IT2.0 . int alter. float c_mark. where the last read in data set becomes the end of the linked list */ void linkstruct(void) { FILE * fp. /* makes a simple linked list from a file */ void list(void).

hp != ZERO. hp->name. &hp->age. } } fclose(fp). } while (!feof(fp)) { if ((hp = (student *) malloc(sizeof(student))) == ZERO) { printf("Not enough memory" "available\n"). hp->age.3. exit(-1). if ((fp = fopen("student. } 5.dat". hp = hp->prev) printf("Name: %s Age: %2d C-Mark: %.03. anchor = hp.0 . "r")) == ZERO) { printf("File cannot be opened for " "reading\n").3 Double linked list _______________________________________________________ Version IT2. exit(-2).99 _______________________________________________________ student *hp. hp->c_mark).Ruth Schubert C-Course 20.2f\n". } if (3 == fscanf(fp. &hp->c_mark)) { /* Link so that the element which was the last one read in becomes the anchor of the linked list */ hp->prev = anchor. for (hp = anchor. "%s %d %f". } /* Output of the simple linked list: */ void liste(void) { student *hp. hp->name.18.

/* Pointer on previous element */ } student. which indicates the next element of the list and a further prev-pointer. then the anchor points to ZERO. which is named anchor.h> #include <stdlib. /* Function declarations: */ void linkstruct(void). /* Pointer on next element */ struct person *prev. the same way.99 _______________________________________________________ A double linked list is characterized by the following: • There is a pointer. which points to ZERO. /* Global pointer on structure for the header of the linked list: */ student *anchor = ZERO. • Each list element contains a next-pointer. If the list is empty. This element was first read in when the list was built.Ruth Schubert C-Course 20. A double linked list is especially suitable for lists.h> /* Structure declaration: */ typedef struct person { char name[30]. to mark the end of the list. int age. float c_mark. the insertion of list elements while keeping an already existing sorting or even deletion of list elements is somewhat easier than in case of simple linked lists. Example  #include <stdio. /* displays the double linked list */ _______________________________________________________ Version IT2. thus to mark the beginning of the list. struct person *next. which indicates the previous list element. and it points to the first element of the list. the first element contains a prev-pointer. • The last element then contains a next-pointer.0 . /* builds from a file a double linked list */ void list(void).03. in addition. which indicates to ZERO. which are to be ran through forwards and backwards rather easily.

exit(-1).0 . exit(-2).03. _______________________________________________________ Version IT2. &hp->c_mark)) { if (anchor == ZERO) { /* The first element should be read in: */ hp->prev = ZERO.dat". student *hp. if ((fp = fopen("student. &hp->age. hp->next = ZERO.99 _______________________________________________________ void main(void) { linkstruct(). Connect structures to a double linked list: */ void linkstruct(void) { FILE * fp. "r")) == ZERO) { printf("File cannot be opened " "for reading\n"). } if (3 == fscanf(fp. } while (!feof(fp)) { if ((hp = (student *) malloc(sizeof(student))) == ZERO) { printf("Not enough memory" "available\n"). /* Display linked list */ } /* Open a fixed preset file for reading and read out data set by data set in structures. "%s %d %f". /* Build Link function structure */ list().Ruth Schubert C-Course 20. *hp2. hp->name.

0 .99 _______________________________________________________ anchor = hp.3.4 Ring link In case of ring links there are also simple and double linked variants. } hp2 = hp.Ruth Schubert C-Course 20. } /* Output of double linked list: */ void list(void) { Student *hp.2f\n". but only the double linked variant is described here. hp->next = ZERO. hp->age. hp != ZERO. } else { /* The read-in element is not the first element. } 5. /* memorize address of old element in hp2 */ } } fclose(fp). A list with ring links is characterized by the following: _______________________________________________________ Version IT2.03. hp->c_mark). hp->prev = hp2. for (hp = anchor. attach new element: */ hp2->next = hp. hp->name.18. hp = hp->next) printf("Name: %s Age: %2d C-Mark: %.

"first element". &anchor /* is its own precursor and successor _______________________________________________________ Version IT2. A list with ring links is characterized by the fact that no difference has to be made between "empty list". /* Anchor is a pseudo-element. Example  #include <stdio. /* Pointer on next element */ struct person *prev.0. "other elements" or "last element" when inserting or deleting elements. but the next-pointer as well as the prev-pointer show in this case the anchor itself. /*Age and C_mark make also no difference */ &anchor.0 . which indicates to the previous list element.99 _______________________________________________________ • There is a pseudo-element of the list. This structure contains no important information whatsoever. int age. which indicates the next element in the list. thus to mark the beginning of the list. If the list is empty.0. thus the program works faster than with other list types. the first element contains a prevpointer. which indicates the next element of the list and another prev-pointer.03. which is marked as an anchor.Ruth Schubert C-Course 20. • The last element then contains a next-pointer. /* Pointer on previous element */ }student. which contains no important information and only containt the pointer "next" for the first and "prev" for the last element: */ student anchor= { "". • Each list element contains a next-pointer. float c_mark. which points out to the anchor. which indicates the anchor.h> /* Structure declaration: */ typedef struct person { char name[30].h> #include <stdlib. /*No name */ 0. the same way. and the prev-pointer. then the anchor still exists. thus to show the end of the list. which indicates the previous element in the list. struct person *next. except for the nextpointer.

/* Function declarations: */ void ringauf(void). student *ptr. /* builds from a file a ring-like linked list */ void list(void). link the structures to a ring-like linked list: */ void ringstruct(void) { FILE * fp.dat". if ((fp = fopen("student. ptr = &anker. /* Call of ring build function */ list(). exit(-2).03. *hp. /* displays the ring/like linked list */ void main(void) { ringstruct().0 .Ruth Schubert C-Course 20. exit(-1). } while (!feof(fp)) { if ((hp = (student *) malloc(sizeof(student))) == ZERO) { printf("Not enough memory " "available\n"). /* Ring display */ } /* Open a fixed preset file for reading and read out data set by data set in structures. } _______________________________________________________ Version IT2.99 _______________________________________________________ */ }. "r")) == ZERO) { printf("File cannot be opened" "for reading\n").

&hp->c_mark)) { /* Precursor of current sentence becomes the Precursor of the new sentence: */ hp->prev = ptr->prev. /* New sentence becomes current sentence: */ ptr = hp. } _______________________________________________________ Version IT2. hp->name. "%s %d %f". hp != &anchor. &hp->age.Ruth Schubert C-Course 20. } } fclose(fp).next. hp->age. /* New sentence becomes the successor of the old predecessor: */ (ptr->prev)->next = hp. hp = hp->next) printf("Name: %s Age: %2d C-Mark: %. /* Current sentence becomes the successor of the new sentence: */ hp->next = ptr. hp->c_mark). } /* Ring output: */ void list(void) { student *hp. /* New sentence becomes precursor of the current sentence: */ ptr->prev = hp.03. hp->name. for as long as the dummy element is reached again: */ for (hp = anchor. /* Set pointer on the first correct element and Display.99 _______________________________________________________ if (3 == fscanf(fp.2f\n".0 .

These knots contain Two pointers. which make sure the trees are balanced (for example AVL-trees). Disadvantages of binary trees · The structure of a binary tree is somewhat complicated.Ruth Schubert C-Course 20. The tree is basically structured in such way. As opposed to a linked list. searching the tree according to a certain structure.4 Binary trees A binary tree is an organisation of same type structures. if one of the branches does not exist. The following features result: Advantages of binary trees · The memory space necessity for the structures can be adapted right to the actual needs during runtime. that structures are sorted according to one or several criteria.) is by using recursive functions (see "Recursive function call" on page 107). There are however algorithms. searching through all elements. Example  _______________________________________________________ Version IT2. and the other in the "right" branch. branches of different length can result according to the incidental occurence of the structures to be implemented in the tree.03. which indicate to a "branch" each (marked as "left branch" and "right branch"). The memory space for each structure within this binary tree is allocated individually. where the individual structures are marked as "knots". The best way to realize functions for handling a binary tree (building the tree. then this is marked by the fact. · When building the tree.99 _______________________________________________________ 5. Each branch consists of a knot with the attached branches. According to this sorting if they are "smaller" than the respective knot they are attachet to the "left" branch.18. where this branch is linked is set to ZERO. They can partly decrease the speed advantages again. that the pointer of the knot. in case of a binary tree it is not a linear but an areal formation. search processes can run very fast. content display of the entire tree etc. because the search does not occur linearly anymore (as in linked lists).0 . · Through the areal structure.

/* Shows nothing in the beginnig */ t_student *ptr. FILE *fp.dat". void main(void) { t_student *root = ZERO. struct person *left.h> #include <stdlib. /* Function declarations: */ /* Searches the correct installation location and introduces The data set: */ t_student * treestruct(t_student *knot.h> /* Structure declaration for binary tree: */ typedef struct person { char name[30].03. float c_mark.0 . "r")) == ZERO) { printf("File cannot be opened " "for reading\n"). } /* read up to file end: */ while (!feof(fp)) { /* Get memory for data set: */ if ((ptr = (t_student *) malloc( sizeof(t_student))) == ZERO) { printf("Not enough memory " "available\n"). _______________________________________________________ Version IT2. exit(-1). t_student *sentence). /* displays the binary tree: */ void t_list(t_student *knot). /* Pointer on left subtree */ struct person *right. int age. /* Pointer on right subtree */ } t_student. /* Open file for reading: */ if ((fp = fopen("student.99 _______________________________________________________ #include <stdio.Ruth Schubert C-Course 20.

Ruth Schubert C-Course 20. ptr->name. release unnecessary Memory space: */ free(ptr). "%s %d %f".03. ptr->right = ZERO. /* Function call. /* display binary tree */ } /* Find installation location and link in new data set: */ t_student * treestruct (t_student *knot. to find the right installation location */ } else /* no entire data set.0 . &ptr->c_mark)) { ptr->left = ZERO. else { /* search correct installation location: */ /* Query 1. } /* Read in data sets: */ if (3 == fscanf(fp.ptr). &ptr->age. } t_list(root). t_student* sentence) { /*Found correct installation location:*/ if (knot == ZERO) knot = sentence. criteria (C_grade): */ if (knot->c_mark < sentence->c_mark) knot->right = treestructu( _______________________________________________________ Version IT2.99 _______________________________________________________ exit(-2). root = treestruct( root.

sentence).03. } } 5. sentence).2f. knot->age). } /* Output of binary tree */ void t_list(t_student * knot) { /* Only to be displayed. } } return knot. else if (knot->c_mark > sentence->c_mark) knot->links = treestruct( knot->left.18. else { /* C-grades are not equal: 2. else knoten->left = treestruct(knot>left.Ruth Schubert C-Course 20. if the knot is not empty: */ if (knot != ZERO) { /* First display the left: */ t_list(knot->left). knot->c_mark. knot->name. Mark: %.99 _______________________________________________________ knot->right. _______________________________________________________ Version IT2.0 . /* Then display itself: */ printf("Name: %s. Age: %d\n". /* Finally display the correct branch: */ t_list(knot->right).5 Hashing Hashing is a method to increase access to linked lists or binary trees. sentence). sentence). Sorting criteria is age */ if (knot->age < sentence->age) knot->right = treestruct( knot->right.

0 .h> #include <malloc. Example  /* Build a hash table from the student data. whose anchors are addressed over the so-called hash table of the preset size (HASHSIZE). if a hash collision appears when building a table.: Meier 47 2. then the entry is set in the next free cell of the table. A good hash algorithm should be made in such way. but pointers to the structures themselves. Finally the user is asked to enter a name and the corresponding data set is searched and displayed through the hash table */ /* Format used in the file: <name> <age> <c_mark> Bsp. where the hash table contains no pointer on part lists or part trees.h> #include <process. In extreme case. that only a part of the list or tree must be searched by using hashing. If the same hash index is calculated for two different structures based upon this algorithm. these lists or trees can show degenerated types with only one structure element. The acceleration consists now of the fact.8 */ /* File name with student data: */ #define IN_FILE "studentdat" #include <stdio. this often leads to superfluous searches. This index is calculated from one or less arbitrary algorithm from the contents of the structures.03. The hash method described here is named "Separate Chaining". table which points out to several linked lists. then we can say this is a hash collision. Apart from this. there is also the so-called "Open addressing".99 _______________________________________________________ The main idea is the division of linked lists or binary trees into several linked lists or binary trees. that the accumulated structures are set in part lists or trees as balanced as possible.h> /* ----------------------------------------------*/ /* Definitions and declarations for linked list: */ _______________________________________________________ Version IT2.Ruth Schubert C-Course 20. The classification of structures into different lists or trees happens based upon the hash index. this is why this technique is not further explained here. which serves as an index for the hash table. which partly cancels the hashing advantage. When searching.h> #include <string.

#define HASHSIZE 10 s_data *hashtable[HASHSIZE]. index < strlen(names).99 _______________________________________________________ typedef struct student { char name[50]. } s_data. struct student *next. return (value % HASHSIZE).0 . /* Run index for passing through the string */ for (index = 0. index++) value += names[index]. This hash function is only suitable. float c_mark.03. int age. */ int hashfunc (char *namen) /* Returns the value of the Hashindex back for the preset name */ { int value = 0. all pointers show at the beginning to ZERO */ /* ----------------------------------------------*/ /* Hash function (is needed for building and read out !) */ /* The hash function selected here: adds all letters in a name. /* Buffer for the sum of letters */ int index. if the name is taken as search criteria.Ruth Schubert C-Course 20. } /* -----------------------------------------------*/ static void linkstruct(void) { _______________________________________________________ Version IT2. /* Hashtable.

0 . } /* Read from file: */ if (3 != fscanf(infile.03. IN_FILE).99 _______________________________________________________ s_data *s_poi. } /* Read in file: */ do { /* Allocate memory: */ if ((s_poi = (sdata *) malloc( sizeof (s_data))) == ZERO) { printf("Memory full\n"). /* Exit. FILE *infile. if nothing readable from the file anymore */ /* Calculate hash index for this record: */ hashindex = hashfunc(s_poi->name). exit(2). /* Record is simply sorted by the already existing one */ _______________________________________________________ Version IT2."%s%d%f". int hashindex."rt"))) { printf("Cannot open data file %s \n".s_poi->name. exit(1). &(s_poi->c_mark))) break. /* Start address for a new structure */ /* Input file */ /* Hashindex of the already handled record */ /* Open input file: */ if (ZERO == (infile = fopen(IN_FILE. &(s_poi->age).Ruth Schubert C-Course 20.

ptr->name.1f\n". /* Search this name in corresponding list: */ for (ptr = hashtable[hashindex]. /* Calculate hashindex for given names: */ hashindex = hashfunc(names). } /* -----------------------------------------------*/ void such(char *names) /* Searches for a name in the database and returns all "hits": */ { int hashindex. display */ } } /* -----------------------------------------------*/ _______________________________________________________ Version IT2. /* Yes. s_data *ptr. ptr = ptr-> next) { if (strcmp(name.99 _______________________________________________________ /* the first in the list is the successor of the current one: */ s_poi->next = hashtable[hashindex]. /* current one becomes the first: */ hashtable[hashindex] = s_poi. ptr->age.0 . } while (!feof(infile)). ptr->name) == 0) /* Found ? */ printf("%s %d %3.03. ptr != ZERO.Ruth Schubert C-Course 20. ptr->c_mark).

/* unused */ unsigned lines :6. } } 5. Example  This example is a Bitfield."exit") != 0) /* As long as "exit" is found in the buffer continue */ { printf("Please enter name (for " "Ending enter \"exit\"): ")..03. /* Who enters a longer one . unsigned paper :1. } dr_status. /* Structure of linked list from a file */ while (strcmp( buffer. This is necessary if: • Memory space must be saved. • Data structures with a lot of information content must be managed (where the elements do not need the numeric range of the basic data types).Ruth Schubert C-Course 20.19 Bit fields In C there is the possibility to display information as individual bits of the bit groups. scanf("%s". unsigned :3. /* Read in names */ /* Search names and display if necessary: */ search(buffer).99 _______________________________________________________ void main(void) { char buffer[200]=" ".0 . */ Linkstruct(). which contains the status bits of a printer: struct { unsigned ready :1. • Interfaces to peripheral devices must be operated. _______________________________________________________ Version IT2.. unsigned blocked:1.buffer).

As in structures..Ruth Schubert C-Course 20. status &= (˜(INIT | WAIT)). Often a bit access is made not with bit fields but with bit masks. separated by a colon.20 Bit masks Example  #define INIT 0x07 #define READY 0x08 #define WAIT 0x10 unsigned int status = 0. The bit width of an element is indicated behind the element name. /* Deleting the bits */ . 5. Fields can be defined by bitfields. The definition of pointers on bit fields is possible. this means in ascending order. /* Setting the bits */ . The individual elements of the bit field must be declared unsigned. 5.line > 30) . if (dr_status.03... _______________________________________________________ Version IT2... if (( status & READY) == 0) /* Query of a bit */ . . The lowest value Bit is first described and the highest value bit the last. elements of different data types can be displayed on the same memory space.0 .. Example  dr_status. A union allocates as much memory space as the largest element needs.99 _______________________________________________________ The definition of a Bit field is made with the keyword struct... at different times.ready = TRUE. the type of a bitfield can be declared. Bit fields are justified to word limits (this means 16 Bits). status |= INIT | WAIT..21 Unions (Variants) With a union. Unallocated bit fields are presented without a name. The elements of a bit field are accessed like structure elements..

f_typ) += *(p2. case 'f': *(p1. declaration.03.c_typ. The type of the address parameter should be characterized by the 3rd parameter. break. the same rules are applied as for structures (see "Simple structures" on page 122). } } _______________________________________________________ Version IT2. break: case 'c': strcat(p1. union will be used. p2. Function definition void func (union par_typ p1.0 . float *f_type.i_typ). char *c_type. Example  A function should be able to process parameters of different data types.f_typ). }.c_typ). break. char p_typ) { switch (p_typ) { case 'i': *(p1. default: printf("Parameter error \n"). The function should do the following: · If the first two parameters are of the type int or float. then it should add the values addressed through the pointer and store the result at the address of the first parameter. break. Declaration of the union-type par_typ: union par_type { int *i_type.Ruth Schubert C-Course 20.i_typ) += *(p2. • In case of char-pointers. Instead of the control word Struct. union par_typ p2. access and pointer.99 _______________________________________________________ For the definition. the second string should be attached to the first string.

sym_tab[i]. _______________________________________________________ Version IT2. } sym_tab[SYM_SIZE].sym_value. sym_tab[i]. Access to an element switch(sym_tab[i]. sym_tab[i]. case 'f': printf("%20s %10f \n".sym_name.0 .c_type).sym_value.99 _______________________________________________________ Example  Declaration of the union type all_typ union all_type { int i_type.Ruth Schubert C-Course 20. break.03. float f_type. sym_tab[i].sym_value. }. break.u_type) { case 'i': printf("%20s %10d \n". char c_type. char u_type.f_type). union all_type sym_value.sym_name. Definition of a structure field symtab (Symbol table) struct { char symname[20]. sym_tab[i].sym_name.i_type). case 'c': printf("%20s %10c \n". sym_tab[i].

_______________________________________________________ Version IT2.03.0 . 6.Ruth Schubert C-Course 20.1 String processing String functions assume that a string is a character sequence.1 strcat Syntax #include <string. 6 Some C-library functions 6.99 _______________________________________________________ break. const char *src). which is ended by \0.1.h> char *strcat(char *dest.

for example strchr(strs. The length of the resulting string is strlen(dest) + strlen(src).0)returns a pointer to the finishing zero of the strs string.h> char *strncat(char *dest. 6. Return value strncat returns dest. _______________________________________________________ Version IT2.h> char *strchr(const char *s.Ruth Schubert C-Course 20.03. const char *src.3 strchr Syntax #include <string.2 strncat Syntax #include <string.1. int c). Description strchr searches a string s in forward direction after the first occurrence of a preset character c. size_t maxlen). The maximum length of the resulting string is strlen(dest) + maxlen. Return value strcat returns a pointer on both strings which are linked together.99 _______________________________________________________ Description strcat appends a copy of the src string to the end of the dest string. Description strncat copies at most maxlen characters of the src string at the end of the dest string and then attaches a string end character (\0).1.0 . 6. The binary zero finishing in the string is thus seen as a being part of the string.

h> int strcmp(const char *s1.1.03. Return value If s1 is.h> int strncmp(const char *s1. Description strncmp makes the same unsigned comparison as strcmp.Ruth Schubert C-Course 20. const char *s2). while it starts with the first character in each string and continues with each next character.then strcmp returns a value: < 0 == 0 >0 _______________________________________________________ Version IT2..99 _______________________________________________________ Return value strchr returns a pointer upon the first occurrence of the character c in the string s .1. size_t maxlen). as far as the corresponding characters do not differ from each other or the end of one of the strings is not yet reached. then strchr returns ZERO. Smaller than s2 Equal s2 Higher than s2 6. Return value .4 strcmp Syntax #include <string.. If c does not appear.0 . Description strcmp performs an unsigned comparison of s1 with s2. 6. const char *s2... strncmp starts with the first two characters in each string and continues with the following character until either different characters were detected or maxlen characters were compared.5 strncmp Syntax #include <string. but does not regard as maxlen character anymore.

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
If s1 is... Smaller than s2 Equal s2 Higher than s2 6.1.6 strcpy Syntax #include <string.h> char *strcpy(char *dest, const char *src); Description strcpy copies src on dest and stops as soon as the string src final binary zero was copied. Return value strcpy returns dest. 6.1.7 strncpy Syntax #include <stdio.h> char *strncpy(char *dest, const char *src, size_t maxlen); Description strncpy copies until maxlen characters from src to dest, where dest is either cut off or finalized with a binary zero. The target string dest is not finalized with a binary zero, if the string length of src is equal or higher than maxlen. Return value strncpy returns dest. 6.1.8 strlen ...then strncmp returns a value: < 0 == 0 >0

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
Syntax #include <string.h> size_t strlen(const char *s); Description strlen calculates the length of the s string. Return value strlen returns the number of characters in s without the zero which finishes the string. 6.1.9 strtok Syntax #include <string.h> char *strtok(char *s1, const char *s2);

Description strtok understands the s1 string as a sequence of no or several keywords (tokens), which are separated by one or several separators of a separator string s2. The first call of strtok returns a pointer to the first character of the first token in s1 and writes a binary zero after s1 immediately after the first token. Further calls of strtok with ZERO as the first parameter work themselves up through the entire s1 string in this way, until there are no more tokens. The separator string can be otherwise defined at each of these calls, according to the needs. Return value

_______________________________________________________ Version IT2.0

Ruth Schubert

C-Course

20.03.99

_______________________________________________________
strtok returns a pointer on the found token in s1. ZERO is returned, if no further tokens are available. Example  #include <string.h> #include <stdio.h> void main(void) { char input[16] = "abc,d"; char *p; p = strtok(input, ","); if (p != ZERO) printf("%s\n", p); p = strtok(ZERO, ","); if (p != ZERO) printf("%s\n", p); }

6.2 Converting character strings to numbers 6.2.1 atoi Syntax #include <stdlib.h> int atoi(const char *s); Description

_______________________________________________________ Version IT2.0

If the string cannot be converted in a number of the desired type (thus long).03. There are no provisions agains overflow. thus atoi detects in the following sequence: · an optional string of tab characters and blanks · ein optional prefix · a string of numbers The first unrecognized character ends the conversion for this function. _______________________________________________________ Version IT2.0 . 6.h> long atol(const char *s). then atoi returns 0. in such case the results are undefined. then atol returns 0. Return value atoi returns the converted numeric value. thus atol detects in the following sequence: · an optional string of tab characters and blanks · an optional prefix · a digit string The first unrecognized characters end the conversion for this function.2 atol Syntax #include <stdlib. If the string cannot be coverted into a number of the desired type (int).2. There are no provisions against overflow. Return value atol returns the converted numerical value back. Description atol converts a string s into a long value. in such case the results are undefined.99 _______________________________________________________ atoi transforms a string s into an integer value.Ruth Schubert C-Course 20.

. but from the buffer field.2. where an optional prefix signed integer number can be appended.99 _______________________________________________________ 6.]). .Ruth Schubert C-Course 20..4 sscanf Syntax #include <stdio. where the numbers can be distributed before or/and after the decimal point · an optional letter e or E.h> double atof(const char *s). this function detects a text representation of a floating point number. Description This function works the same way as scanf (see "Input with scanf" on page 45) with the difference. Description atof converts a string s into a double-value. Return value _______________________________________________________ Version IT2.0 . Return value atof returns the transformed numeric value back from the s string. The first undetected character ends the conversion for this function. which is made of the following elements: · an optional string of tab characters and blanks · an optional prefix · a string of digits and an optional decimal point. const char *format[.h> int sscanf(const char *buffer.03.3 atof Syntax #include <math. 6.2. that it does not read from a stream. address.

In case of error (if no fields were stored) then 0 is returned. but not stored input fields. Name of macro Meaning: character Numeric range is.. this counting does not include the read in.Ruth Schubert C-Course 20. isalnum Letter or digit ('A' <= c <= ('a' <= c <= ('0' <= c <= isalpha Letter ('A' <= c <= 'Z') or 'z') or '9') 'Z') or _______________________________________________________ Version IT2. converted and stored input fields.0 . Description The macros serve for verifying the character features. If sscanf tries to read at the end of a string (thus the binary zero which ends the string).. sscanf returns the number of successfully read-in.03.99 _______________________________________________________ In case of success. 6.3 Macros for verifying character features Syntax #include <ctype. then EOF is returned.h> int <macro>(int c).

..4 Macros for character conversion 6..h> int tolower(int ch).Ruth Schubert C-Course 20. All other characters remain unchanged. _______________________________________________________ Version IT2.. numbers and letters (9 <= c <= 13) or (32 == c) ('A' <= c <= 'Z') ('A' <= c <= 'F') or ('a' <= c <= 'f') or ('0' <= c <= '9') isascii iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit ASCII-character Control character Digit Visible character Small letter Printable character Punctuation mark Empty characters of all type Capital letters Hex number Return value These macros return TRUE (thus a numeric value different of 0). 6.z).99 _______________________________________________________ ('a' <= c <= 'z') 0 <= c <= 127 (c == 127) or (0 <= c <= 31) ('0' <= c <= '9') Printable character without blank ('a' <= c <= 'z') Printable character with blank Printable character except for blank. if c is found within the preset numeric range.4.0 .Z) ch into a small letter (a. Description tolower converts a capital letter (A.03.1 tolower Syntax #include <ctype. otherwise FALSE (0).

6..4.Z). _______________________________________________________ Version IT2. 6.1 rand Syntax #include <stdlib.0 .. pseudo-random numbers can be taken from a random number generator. Return value toupper returns the converted value of ch as a capital letter. otherwise toupper returns ch.h> int toupper(int ch).5.h..h> int rand(void).99 _______________________________________________________ Return value tolower returns the converted value of ch as small letter. otherwise tolower returns ch. All other characters remain unchanged. 6.03. Description rand uses a random number generator with an extent of 232 for generating Pseudo-random numbers in the range between 0 and RAND_MAX. The constant RAND_MAX is defined in stdlib. Description toupper converts a small letter (a.. as far as ch has a small letter.z) ch into a capital letter (A. which can be initialized with the srand function.2 toupper Syntax #include <ctype.5 Random numbers generator Using the rand function. Return value rand returns the generated pseudo random number.Ruth Schubert C-Course 20. as far as ch is a capital letter.

Ruth Schubert C-Course 20. Description The random number generator is only started. i++) printf("%d\n".h> #include <stdio. The random number generator can be set on another start value.03. Example  /* In this example the time in seconds is simply used as a parameter for 'srand'. for(i=0. by calling srand with seed = 1. Return value None. printf("10 random numbers from 0 to 99\n\n").5. Same seed-values guarantee identical sequences of random numbers.h> void main(void) { int i. } 6. rand() % 100).99 _______________________________________________________ Example  #include <stdlib.h> _______________________________________________________ Version IT2.h> void srand(unsigned seed).0 .h> #include <time. by selecting another value for seed. this way other random numbers are generated at each program call */ #include <stdlib.h> #include <stdio. i<10.2 srand Syntax #include <stdlib.

99 _______________________________________________________ void main(void) { int i.6 Program ending Syntax #include <stdlib. } 6. _______________________________________________________ Version IT2. for(i=0. from which the program was started. srand((unsigned) time(&t)).03. printf("10 Random numbers from 0 to 99\n\n"). Before program end. Return value None. Description exit ends the running program. time_t t. all open files are closed and buffered outputs which wait for output are written.h> void exit(int status). status is provided to return an error status to the operating system. Usually. i<10.0 . rand() % 100). zero means an error free program end and all other values some type of error. i++) printf("%d\n".Ruth Schubert C-Course 20.