Programming in C First meeting 5.9.2016 Tiina Niklander Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 1
Learning goal objectives Language structures, data structures, modules, functions+parameters Files Pointers, structured elements Using properly dynamic and static data structures like tables, lists, queues, stacks, trees (from data structures and algorithms course!) NOTE: No C++ features allowed in exam. pure ANSI C only Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 2
Course structure No weekly exercise deadlines, but goal is to do weekly. lectures on Mondays Official course page: https://courses.helsinki.fi/fi/tkt21008/ Course structure is in wiki: https://wiki.helsinki.fi/display/cprogramming2015/ Exercise submission on our own server: http://tmc.mooc.fi/hy The course: Programming in C, 2018-2019 Grading based on Examinarium exam only - course is a mix of self-study course and support structures (= lectures & guidance) Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 3
Exam Paper-based exam on computer No compiler No man pages No book or other material available Exam will have 4 questions, group names are Command-line arguments Arrays and/or other data types Files Linked lists Exam question randomly selected for each group Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 4
Examinarium exam No fixed schedule (exam time 175 minutes) Register and select your own exam time in https://examinarium.helsinki.fi/enroll/tkt21008/exa m/9909 This course s exam will be open until end of May. You can try only once until your answer is graded Retry possible only once you know the result of previous exam Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 5
Course material Use a course book! ONE good C course book is a MUST: Kernighan & Richie: C programming language Müldner : C for Java programmer King: C Programming, A Modern Approach Tens of other options also exists Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 6
TMC test my code TMC checks automatically the programming tasks and maintains the list of accepted tasks. Online tool, so can be used from home or at university If needed: there will be guidance session (2 hours per week) in computer class room. Possibility to get teacher review (must be submitted for review!) Please use only when needed to keep the review queue manageable Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 7
C language C assumes that programmer is intelligent enough to use all of its constructs wisely, and so few things are forbidden. Closely tight with UNIX same original developers Low-level language explicit memory allocation and deallocation! allows operations on the memory addresses and bit-level allows dynamic type changes of variables important concept: POINTER (= memory address) C can be a very useful and elegant tool. People often dismiss C, claiming that it is responsible for a bad coding style. The bad coding style is not the fault of the language, but is controlled (and so caused) by the programmer. Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 8
Comparison of C and Java from Müldner: C for java programmers uprimitive data types: character, integer, and real. In C, they are of different sizes, there is no Unicode 16-bit character set ustructured data types: arrays, structures and unions. In C, arrays are static there are no classes ucontrol structures are similar ufunctions are similar www.cs.helsinki.fi
Comparison of C and Java ujava references are called pointers in C. ujava constructs missing in C (ANSI): packages threads exception handling garbage collection standard Graphical User Interface (GUI) built-in definition of a string standard support for networking support for program safety. www.cs.helsinki.fi
C key features Low level language: Memory address and value are visible Pointer is a variable that stores an address Old language: No objects No garbage collection Explicit memory management Functions to allocate and free memory areas Dynamic memory allocations in heap Static variables in stack stack heap static global variables code Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 11
Xptr DC 0 X DC 12 LOAD R1, =X ; R1 230 STORE R1, Xptr LOAD R2, X ; R2 12 LOAD R3, @Xptr ; R3 12 Addresses and values Xptr=225: memory 230 12345 TITO Variable X s address is 230 (&X) Variable X s value is 12 (X) Pointer Xptr s address is 225 (&Xptr) X=230: Pointer Xptr s value is 230 (Xptr) Address of some data (now the address of X) The value of the integer (*Xptr) that Xptr points to is 12 In C language as: Y = *Xptr; /* value of the location Xptr points to */ 12556 128765 12222 12 12998 Faculty of Science Department of Computer Science 5.9.2018 12
Modular programming in C C does not support objects or modular programming, but it has features that can be used to mimic them - Functions and function prototypes - Header files Using these features you can separate the interface and implementation *.c hidden implementation *.h public interface Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 13
Standard libraries Each library contains a set of useful functions A header file gives the function signatures and type definitions for that particular library stdio.h math.h assert.h is usually always used, since it contains the functions for reading and writing contains mathematical functions macro assert to help locate mistakes 29 header files in total (see wikipedia for the list) Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 14
Example program #include<stdio.h> /*Header file of a library*/ int main(int argc, char **argv) /* The main function */ { int x, *y, z; /*Variable Declaration*/ if ( (y = malloc (sizeof(int)) ==NULL) return(1); x = 5; *y = 10; z=x+*y; printf ("The sum is %d", z); free(y); return (0); /* standard return value for success */ } Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 15
Programming style Write clear and easily understandable code (Java programming course style is good!) Cryptic and concise code has no value itself, the clarity is more important do { if (scanf( %d, &i)!=1 i == SENTINEL) break; if (i>maxi) maxi = i; } while (1); void show (char *p) { char *q; printf( [ ); for (q=p; *q!= \0 ; q++) printf( %c, *q); printf( ]\n ); } www.cs.helsinki.fi
Macro Function calls Function ends #include<stdio.h> #include<string.h> #define SUCCESS 0 #define FAILURE -1 int main(void) { char pass_buff[50] = {0}; printf("\n Enter the password..."); //Get the password from user fgets(pass_buff,sizeof(pass_buff)-1,stdin); //Make sure that the extra(last) character //picked up from stdin is washed off } } //from buffer. pass_buff[strlen(pass_buff)-1] = '\0'; if(! (strcmp(pass_buff,"linux"))) { // Passwords match printf("\n Passwords Match..SUCCESS\n"); return SUCCESS; } else { // Passwords do not macth printf("\n Passwords do not match...failure\n"); return FAILURE; Faculty of Science Department of Computer Science Another example Emply lines would make it more readable Main function From: mylinuxbook.com Array = continuous memory area (here string) 5.9.2018 17
Programming in C Command-line interface needs only shell, no graphical interface the old fashioned way most UNIX experts still do it this way explicit compilation and linking Integrated Development Environments (IDEs) TMC is integrated with NetBeans Eclipse is another very popular one Program still needs to be compiled and linked before execution IDE might hide these phases Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 18
Development process with command-line interface Write program Using suitable editor (vim, nano, emacs,...) Must produce plain text file Compile Link Select the correct compiler and arguments (gcc -c) Link the compiled modules to form a program (gcc) Execute Executing or running the program www.cs.helsinki.fi
Compiling (short program, all in one file) Compile gcc helloworld.c or gcc o helloworld \ helloworld.c Compiler does preprocessing, actual compilation and linking... and produces the executable file a.out or int main (void) { printf( Hello world \n ); return 0; } helloworld www.cs.helsinki.fi
gcc --help Usage: gcc [options] file... Option -- help lists all possible options and features of the compiler, there are plenty -c compile and assemble, but do not link -o <file> place the output into <file> www.cs.helsinki.fi
Compiling: gcc -ansi -pedantic -Wall int main (void) { printf( Hello world \n ); return 0; } Options Wall and pedantic show all possible warnings (used by TMC) Option ansi makes sure that the compiler follows standard (some differences in gcc exist) gcc -ansi -pedantic -Wall -o helloworld helloworld.c /home/fs/niklande/c-luennot/esimerkit/helloworld.c: In function `main': /home/fs/niklande/c-luennot/esimerkit/helloworld.c:3: warning: implicit declaration of function `printf' Faculty of Science Department of Computer Science #include <stdio.h> int main (void) { printf( Hello world \n ); return 0; } www.cs.helsinki.fi 5.9.2018 22
Structuring a small C program: order of elements in the file #include directive to use (standard) libraries and header files Defining constants and types Easy to locate, modify and control Function prototypes (before the function in used) Function main (every program has one) execution starts here and ends when the main returns. Function definitions (=code of the function) Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 23
What if you have a larger project? - Split to multiple files and libraries main sub1 sub2 sub3 sub4 subsub1 subsub2 subsub2 Functions of standard libraries Modularity at the function level Programmers own libraries of functions Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.201824
Multiple modules (separate source files with headers) /* main.c */ #include <stdio.h> #include eka.h #include toka.h int main (void) { eka(); toka (); return 0; } /* eka.c */ #include <stdio.h> #include eka.h void eka (void) { puts( eka ); } /* eka.h */ /* toka.c */ #include <stdio.h> #include toka.h void toka (void) { puts( toka ); } /* toka.h */ Could write everytime: void eka (void); gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Faculty of Science Department of Computer Science void toka (void); www.cs.helsinki.fi Instead, use makefile 5.9.2018 25
Program has multiple files and modules Every program file is compiled separately to create object module (or library) gcc c main.c The modules are then linked together to form the complete program gcc o program main.o eka.o toka.o Usually compiled with make (executes a sequence of commands) www.cs.helsinki.fi
makefile gcc c main.c gcc c eka.c gcc c toka.c gcc o ohjelma main.o eka.o toka.o Create makefile once, use it multiple times make NOTE: tab, not spaces # makefile CC = gcc ansi pedantic Wall ohjelma: main.o eka.o toka.o $(CC) o ohjelma main.o eka.o toka.o eka.o: eka.c eka.h $(CC) c eka.c toka.o: toka.c toka.h $(CC) c toka.c main.o: main.c eka.h toka.h $(CC) c main.c www.cs.helsinki.fi
After compiling and linking? We have executable program, but does it work? Try to execute it and test the program Look for errors, locate mistakes - Extra print statements - Read the code, simulate execution, THINK! - Use debugger Write automated tests, evaluate test coverage ( -> course: Software testing) On this course we are satisfied with smoke testing or sanity check. (Program seems to satisfy the desciption.) www.cs.helsinki.fi
Testing Target: find mistakes Covers wide spectrum of possible input values Can be automated (using scripts or special test tools/packages) Not part of the learning goals of this course On this course (smoke test, sanity check) usually enough to check - Correct and incorrect input values - Boundary values(-1,0,1) www.cs.helsinki.fi
Extra print statements #ifdef EXTRAPRINT printf ( Fname: Variable name %d \n, variable); #endif Target: try to understand the functionality of the code. Placed: around the most probably mistake location Usually more handy than debugger, if you have an idea of the error location in advance. gcc D EXTRAPRINT www.cs.helsinki.fi
More advanced tools : assert and valgrind assert macro (in assert.h) helps to check the values of variables same code can be compiled with and without the assert checks Write the asserts in the source code (*.c file) memcheck from valgrind makes it possible to find incorrect memory usage used in some of the acceptance tests run at the tmc server used at run time, execute program within valgrind Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 31
Debugger gdb (gdb) help List of classes of commands: aliases -- Aliases of other commands breakpoints -- Making program stop at certain points data -- Examining data files -- Specifying and examining files internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands www.cs.helsinki.fi
core dump Crashed program usually produces a file (code dump) that contains state of the memory and registers at the time of crash. This file can be accessed by debugger to find out values of variable and the location of the instruction that crashed the program. This is not covered on the course, but could be very useful to study at some point. www.cs.helsinki.fi
Week1 exercises cover (lecture Mon 10.9.) Learning points: Naming and visibility aspects Variables and simple types (int, float, char) Arrays (=sequence of values in memory) Some standard functions (and using man pages) Input and output Scanf, printf (getc, ) Formatting Stdin, stdout and stderr Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 34
Other Weeks Week2 (17.9.): Pointers, strings, linked lists Presedence and associativity of operators, dynamic memory allocation, address arithmetics Week3 (24.9.): Files Week4 (1.10.): Arrays, command line arguments Pointer arrays, multi-dimensional arrays, Week5 (8.10.): Macros, function pointer, struct, union Week6 (15.10.): Intrusive linked list, bitwise operations Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 35
If time, solve the following problem Design a program that reads n integer values and then determines and outputs whether the sequence entered is sorted in ascending order, decending order, or is unordered. Here is a sample dialog produce by the running program How many integers do you have? 4 Enter the 1st integer: 10 Enter the 2nd integer: 8 Enter the 3rd integer: 6 Enter the 4th integer: 4 Your sequence is sorted in decending order. From: Uckan, Problem solving with C. McGrawHill, 1999. Faculty of Science Department of Computer Science www.cs.helsinki.fi 5.9.2018 36