About these lectures C A short introduction Stefan Johansson Department of Computing Science Umeå University Objectives Give a short introduction to C and the C programming environment in Linux/Unix Go into depth of C Pointers, arrays, structures, preprocessing Introduce Make and makefiles Modeling and Simulation: C intro 2 Recommended readings Books Hanly and Koffman. Problem Solving and Program Design in C. 6th Ed., 2010. ISBN 978-0-321-60151-3. Hanly and Koffman. C Program Design for Engineers. 2nd Ed., 2001 Web-based tutorials and reference pages C Tutorial http://www.cprogramming.com/tutorial.html#ctutorial The GNU C library http://www.gnu.org/s/libc/manual/html_node/index.html Numerical Recipes in C http://www.nrbook.com/a/bookcpdf.php Local The man-pages on Linux/Unix is an excellent reference manual. Just type man followed by the C function name (available in a standard C library) Modeling and Simulation: C intro 3 A C program Source files (extension.c) The code... Header files (.h) Function prototypes, user-defined types, and preprocessing directives Libraries (.a or.so;.lib or.dll in MS Windows) A library is a collection of functions and symbols Every C implementation includes a set of standard libraries, e.g., for I/O- and math-operations Each library has a header file associated to it. Must be included to get access to the functions in the library Modeling and Simulation: C intro 4
Compilation Compile with GNU C compiler gcc > gcc myprogram.c What does gcc do? Preprocessing Compilation Assembly Linking Executable output is by default called a.out Compilation (cont.) Options (see gcc s man-pages for more options) -o file Place output in file file -Wall Issue the most common warnings (recommended) -pedantic Issue all the warnings demanded by strict ISO C -O2 Optimize -O3 Optimize even more -g Stores information for the debugger Modeling and Simulation: C intro 5 Modeling and Simulation: C intro 6 The source file Preprocessor directives Preprocessor directive Function header Comment A comment begin with /* and end with */ End of main function #include <stdio.h> int main(void) { /* Include function body here */ } return (0); Each executable statement must end with a semi-colon (;) Begin with # Instructions to the C preprocessor how to modify the C source before the code is compiled Common directives are #include and #define Modeling and Simulation: C intro 7 Modeling and Simulation: C intro 8
Preprocessor directives (cont.) Identifiers Examples #include <stdio.h> #include myheader.h #define PI 3.14 By convention, written in all capital letters Include the standard header file stdio.h Include the user written header file myheader.h Exchange every occurence of PI in the code with 3.14 Names of functions, variables, etc. Uppercase and lowercase letters matters Valid user-defined identifiers Can only consist of letters, digits, and underscores Cannot begin with a digit Reserved words cannot be used Avoid using more than 31 characters Use meaningful names! Modeling and Simulation: C intro 9 Modeling and Simulation: C intro 10 Fundamental data types Integral types short, int, long, and long long Exist also in unsigned versions, e.g., uint (unsigned int) char Used for representing one character Floating-point types float, double, and long double Variables A variable must be declared before it can be referenced (used) A variable is deallocated when the function returns It s good practice to declare all variables in the beginning of a function, but it is not necessary Variables are not initialized to zero Modeling and Simulation: C intro 11 Modeling and Simulation: C intro 12
Variables (cont.) Variables (cont.) Syntax data_type variable_list; Examples int nr_pigs; double weight, tot_weight; Variables can be initialized at declaration int nr_pigs = 10; Good practice to initialize all variables Constants are declared using const const int a_constant_var; Variables declared with static are not deallocated until the program terminates Used to preserve a value between calls to a function Should normaly be avoided Modeling and Simulation: C intro 13 Modeling and Simulation: C intro 14 Global variables A variable declared outside of a function is called a global variable A global variable can be referenced by all subsequent functions A local variable with the same name will hide the global Global variables should be avoided! Type casting Conversion of a variable of one data type to another data type. Must be done for assignment between variables of different types Automatic type casting is done by the compiler for standard numeric data types Modeling and Simulation: C intro 15 Modeling and Simulation: C intro 16
Automatic type casting double int int a; double b = 1.524; a = b; a = 1 int double int a = 1; double b; b = a; b = 1.0 Automatic type casting int k = 5, m = 4, n; double x = 1.5, y = 2.1, z; Mixed expression k + x 6.5 int double z = k / m; z = 1.0 (1.25) double int n = x y; n = 3 (3.15) Modeling and Simulation: C intro 17 Modeling and Simulation: C intro 18 Explicit type casting Syntax (new_type) expression Examples z = (double)(k / m); z = 1.0 z = (double)k / (double)m; z = 1.25 Functions The type of the return value Function name Input arguments void myfunction(double arg1, int arg2) { /* Function body */ } Function body enclosed with braces void is used when the function does not return a value Modeling and Simulation: C intro 19 Modeling and Simulation: C intro 20
Functions (cont.) A function must be declared before it can be referenced A function can only call other functions declared above in the code Work-a-round Include a function prototype in the beginning, or, even better, in a header file Syntax ftype fname(arg_type_list); void myfunction(double,int); Note the semi-colon in the end and that only the types of the input arguments need to be given Modeling and Simulation: C intro 21 Functions (cont.) The return statement is used to return a value from a function Only one value can be returned Syntax return expression; Examples return 0; return(a+b); return; Can be written with or without parentheses Return from a function without return value Modeling and Simulation: C intro 22 The main function The function main is the first function that is executed in C programs Working as an interface between the calling environment and the program Should only include necessary code for initializing the program Call other functions to do the work! Return 0 (zero) if executed without error, otherwise a non-zero integer value The main function (cont.) A program without input arguments int main(void) {... } A program with input arguments int main (int argc, char *argv[]) {... } Number of arguments Argument vector Modeling and Simulation: C intro 23 Modeling and Simulation: C intro 24
Text output Print to screen (require stdio.h) Syntax int printf(const char format,...); int a = 3; printf( The value of a is %d\n,a); List of variables to be printed %d is called a placeholder (here for an integer). Always begins with %. Other common placeholders are: %c (character), %s (string), %f (floating-point number), and %e (floating-point number in scientific notation) \n writes a newline escape sequence Operators True/False A nonzero value (usually 1) is true Zero (0) is false Relational and equality operators <, >, <=, >=, ==,!= Do not mix-up == (equality) with = (assignment) Logical operators && (and), (or),! (not) Modeling and Simulation: C intro 25 Modeling and Simulation: C intro 26 Compound arithmetic operators Assignments +=, =, =, /=, and %= Example a = a + b; a += b; Incremental a++ : increase a by one (eq. to a = a + 1) b-- : decrease b by one (eq. to b = b 1) The for statement Syntax for ( initialization expression; loop repetition condition; update expression) { statements } Example for (i = 0; i < n; i++) { /* Do something */ } Modeling and Simulation: C intro 27 Modeling and Simulation: C intro 28
Pointers A pointer holds a memory adress to where some data is stored Denoted by a star ( ) at declaration int *nr_pigs; Pointer to an int No memory is allocated for the storage of the data. Must be done explicitly! Do not forget to deallocate memory! Pointers (cont.) int *a, b Access the data to which the pointer points to Star ( ) before pointer *a = 6; b = *a; Get the adress where a variable s data is stored And (&) before variable a = &b; Modeling and Simulation: C intro 29 Modeling and Simulation: C intro 30 Pointers (cont.) NULL as the value of a pointer indicates points to nothing Often used as return-value when something has gone wrong Good practice to initialize a new pointer to NULL int *nr_pigs = NULL; A void pointer is a pointer with no assigned data type void *unknown_type; Allocating/deallocating memory All functions for (de-)allocating memory require stdlib.h Allocate size bytes and return a pointer to the allocated memory void malloc(size_t size); Allocate memory for an array of nmemb elements of size bytes each and return a pointer to the allocated memory. The memory is initialized to zero void calloc(size_t nmemb, size_t size); Modeling and Simulation: C intro 31 Modeling and Simulation: C intro 32
Allocating/deallocating memory Free the memory space pointed to by ptr void free(void ptr); Reallocating void realloc(void ptr, size_t size); Get size of a data type (value of size above) size_t sizeof(type) Each malloc/calloc must be followed by a free! size_t corresponds to the integral data type returned by the language operator sizeof. It is machine dependent and usually an unsigned int or Modeling and Simulation: C intro 33 Pointers Example #include<stdio.h> #include<stdlib.h> int main(void) { int *a, *b; int x = 5; a = malloc(sizeof(int)); if ( a == NULL ) { fprintf(stderr, Failed to allocate memory! ); return (0); } *a = 2; b = &x; x = *a; printf("a = %d, b = %d, x = %d\n",*a,*b,x); free(a); return (0); Check that memory allocation didn t fail. If so, print an error message and exit. What is printed? Do not forget to free } allocated memory! unsigned long int. Modeling and Simulation: C intro 34 Arrays Arrays (cont.) An array is a data structure with indexed elements of the same data type Lists, vectors, etc. (one-dimensional) Matrices, Grids, etc. (two-dimensional) At declaration, the size is given in pair of brackets Tip: For arrays with static size, define the size with #define #define MAX_LENGTH 10... int list[max_length]; Modeling and Simulation: C intro 35 Declaration One-dim. array list with 5 integers int list[5]; Two-dim. array A of size 25 10 int A[25][10]; Initialization at declaration int list[] = {4,1,5,9,1000}; int A[3][2] = {{2,1},{3,4},{10,5}}; int B[][10] = {{3,4,1},{1,10,3,9}}; Modeling and Simulation: C intro 36
Arrays (cont.) The array subscript is enclosed in brackets The array subscript must be in the range 0 (zero) to one less than the length of the array It is up to the programmer to check validity of subscript Referencing elements outside the range may cause unwanted side effects or the program to crash Arrays (cont.) Assignment int list[2], elem0, elem1, elem2; list[0] = 1; elem0 = list[0]; elem1 = list[1]; elem2 = list[2]; Ok Problem Invalid! Modeling and Simulation: C intro 37 Modeling and Simulation: C intro 38 Arrays (cont.) The array name is a pointer to the first element in the array Possible to reach other memory cells by using the pointer list; list+1 is the next address. Note! Pointer arithmetic (list+1) is the value of the next integer Similar expressions list &list[0] list[0] *list list[3] *(list+3) Arrays (cont.) Multi-dimensional arrays (e.g., matrices) s double A[5][6], B[3][8][10][10]; Similar expressions A &A[0][0] A[0][0] **A A[1][3] *(A[1]+3) Modeling and Simulation: C intro 39 Modeling and Simulation: C intro 40