CS 414 C Programming Tutorial Ben Atkin batkincs
CS 414 C Programming Tutorial Ben Atkin batkin@cs. cornell. edu
Why use C? § C is not "safe" § It assumes you know what you're doing § It has a lot of scope for bugs § It's a good systems programming language § Not much is hidden § Faster than Java, more predictable performance § It has all the low-level operations CS 414 C Programming Tutorial 2
Types § No Boolean type, use int: "false" is 0, true is non-zero § Structures for grouping related data § "Like Java classes, but no methods" typedef int pid_t; /* for clarity */ struct pcb { pid_t pid; file_t openfiles[MAXOPENFILES]; . . . } typedef struct pcb_t; /* rename */ CS 414 C Programming Tutorial 3
Constants #define KB 1024 #define MB (KB*1024) /* constant */ /* note brackets */ /* wrong! '; ' causes compile error */ #define WARN(s) fprintf(stderr, s); /* alternative constant definition: PROC_READY==0, PROC_RUNNING==1, . . . */ enum { PROC_READY, PROC_RUNNING, . . . }; /* give it a name */ typedef enum { PROC_READY, PROC_RUNNING, . . . } proc_status_t; CS 414 C Programming Tutorial 4
Dynamic memory allocation § Memory must be explicitly allocated and freed #include <stdlib. h> int main() { /* declare and allocate memory */ int *ptr = (int *) malloc(sizeof(int)); *ptr = 4; /* use the memory */ free(ptr); /* free it for re-use */ } CS 414 C Programming Tutorial 5
Example memory layout 0 x 0 code Immutable heap Dynamic allocation malloc(), free() stack Function calls, local variables 0 x 2000 0 x 50000 CS 414 C Programming Tutorial 6
Pointer initialisation § Always initialise, even if only to NULL #include <stdlib. h> int main() { int x = 5; int *ptr; x = *ptr; /* unpredictable: initialise! */ ptr = &x; /* good initialisation */ *ptr = 4; /* bad initialisation */ *ptr = NULL; /* good 5 */ } CS 414 C Programming Tutorial 7
Changing pointer types § Pointers can be converted between types § type_t *x = (type_t *) y; § (void *) equivalent to any type, e. g. implementation of generic collections § malloc() returns a void * § Useful for low-level operations § e. g. networking, memory allocation CS 414 C Programming Tutorial 8
Parameter passing § Functions can take pointer arguments int function(int *in, int *out); § Two main purposes § So that function can modify the variable (pass-byreference) § Efficiency: passing "big_struct_t x" is not efficient, passing &x is efficient § Return values are often used to signal errors § e. g. return value 0=="no error", non-zero==error CS 414 C Programming Tutorial 9
Parameter passing void function(int *arg 1, char **arg 2) {. . . } int main(void) { int x = 5; int *y = &x; char string[] = "Hello, world!"; char *ptr = NULL; function(&x, NULL); function(y, &ptr); /* *ptr can be changed */ function(y, &string); /* probably wrong */ } CS 414 C Programming Tutorial 10
Pointers and functions /* function returning integer */ int func(); /* function returning pointer to integer */ int *func(); /* pointer to function returning integer */ int (*func)(); /* pointer to function returning pointer to integer */ int *(*func)(); Hide this complexity with typedefs! e. g. typedef void (*interrupt_handler)(void *); void an_interrupt_handler(void *arg); CS 414 C Programming Tutorial 11
Multiple modules typedef struct {. . . } queue_t; void queue_init(queue_t* q); #include "queue. h" void queue_init(queue_t* q) {. . . }. . . CS 414 C Programming Tutorial Standard library #include <stdio. h> #include "queue. h" int main() { queue_t queue; queue_init(&queue); . . . } 12
External definitions /* defs. h */. . . extern int tickcount; . . . #include "defs. h" int tickcount = 0; void set_timer() { printf("Timer at %d. ", tickcount); } CS 414 C Programming Tutorial #include <stdio. h> #include "defs. h" int main() {. . . if (tickcount > 5) set_timer(); } 13
Hints and tips § Avoid bugs in your program: § don't index past the end of an array § don't return pointers to local variables from functions § initialise data properly, especially pointers § check error codes (no exceptions in C) § free() what you malloc() § destroy all pointers to what you free() §. . . or else you might only find them when you least expect it! CS 414 C Programming Tutorial 14
Hints and tips § Program safely! § Plan before you start § Pay attention to compiler warnings § Use assert()to check conditions are valid § Indent your code to make it easy to read § Beware of complicated #defines § Use the debugger § If you're serious about C, get K&R § Lots of library functions for you to use CS 414 C Programming Tutorial 15
- Slides: 15