C For Java ProgrammersWhy C?Why not C?Common Constructs in C and JavaC Types: PrimitivesC Types: structC Types: enumC Types: pointersC Types: arrays and stringsC Types: typedefC Types: void*C Functions: function pointersC Functions: parameter passingC Functions: prototypesC Traps: memory managementC Traps: local variablesC PreprocessorMost Common C LibrariesMulti-file project layoutSlide 20Where to go from here?C For Java ProgrammersTom RoederCS415 2005spWhy C?The language of low-level systems programmingCommonly used (legacy code)Trades off safety for speedClear mapping from C statements to operationsSimple to understand, imperative languageWell-understood common optimizationsWhy not C?Explicit memory managementMemory leaksInvalid pointersNo (built-in) exception handlingNot type safePoor separation of concernsNo good language support for modularizationToo close to assemblyCommon Constructs in C and JavaLoopsif() {}for(;;) {}while() {}do {} while()Functionsint call_me(float a) {return (int)a;}int temp = call_me(3.14);C Types: PrimitivesOften architecture-dependentint, short, longCan count on short <= int <= longfloat, doubleCan usually count on float <= doublecharOne byte per characterUnicode WCHAR in Windows: two bytesC Types: structOften need to define object-like storage unitsC only encapsulates data, not methodsstruct is the unit of encapsulationstruct pos {float x;float y; } p;p.x = 0.7; p.y = 0.1;C Types: enumWhen you need to write code likeColor x = RED;enum { BLUE, RED, GREEN };We’ll get to how to define the Color symbolenums are actually underlying ints.Can have any value at allenum { BLUE = 7, RED = 137, GREEN };GREEN will have value 138.C Types: pointersA pointer contains the starting address of the memory for a given valueint y = 0;int* x = &y;*x = 10; /* y is now 10 */Explicit dynamic memory managementint* x = malloc(sizeof(int)*z);free(x);C Types: arrays and stringsAn array is just a pointer (0-based)int x[5] = {10, 20, 30, 40, 50};x[3] == *(x + 3);A string is just an array of charactersint main(int argc, char** argv) { printf(“arg 1: %s\n”, argv[0]);printf(“char 1: %c\n”, argv[0][0]);}Remember to terminate your string with ‘\0’See string.h for functions: strcmp, strcpy, …C Types: typedefWhen you want to define a new type:typedef int bool;typedef enum { FALSE = 0, TRUE } bool;typedef struct queue_t {void* elt;queue_t* next;} queue;Can be ill-used: (as in Microsoft)typedef int* INTPC Types: void*void* is a pointer to any typeExtremely useful in generic data structurestypedef struct queue_t {void* elt;queue_t* next;} queue;queue* q;…*(int*)(q->elt) = 137;C Functions: function pointersUnlike in Java, we don’t have any reflectionWe can nonetheless pass functions aroundint call_me(float a) { return (int)a;}…int (*fp)(float) = &call_me;printf(“fp gives %d\n”, (*fp)(3.0));Simply passing the address of the functionC Functions: parameter passingTwo methods in CBy valueBy referenceint swap(int a, int b);int swap(int* a, int* b); int swap(int& a, int& b);In Java, all reference types are passed by referenceC Functions: prototypesA function in C must be declared before usedThus you often give the signature twice:int call_me(float a);int main(int argc, char** argv) {return call_me(3.0);}int call_me(float a) {return 1;}C Traps: memory managementDon’t forgot to free memory you’ve alloc’edArrays are not bounds checked in CSet all pointers to NULLwhen they are initializedwhen they are freedRequires strict discipline, and you will forgetUse Purify (if on *NIX, use valgrind)Always check to see if a pointer is NULL before using it.C Traps: local variablesSimple example:char* get_name() {char temp[NAME_LENGTH];/* get something into temp */return temp;}temp is allocated on the stack; you will have an invalid pointer.C PreprocessorUsed for constants and simple replacements#define PI 3.14#define DEBUG 1Also used for macros with arguments#define max(x,y) ((x)>=(y) ? (x):(y))Conditional compilation#if DEBUG#endifincludes: #include <stdio.h>Most Common C Libraries<stdio.h> : standard I/Oprintf (format, …);printf(“Hello there, %s\n”, “Tom”);%s – strings%c – characters%d – integers%f – float%lf – double<stdlib.h>: useful functions:exit, malloc, freeMulti-file project layoutDivide the code into functional unitsEach unit has a .h and a .c filePut the prototypes in the .h and the functions in .cTo make sure that .h files aren’t included more than once, for myfile.h, we do:#ifndef __MYFILE_H_#define __MYFILE_H_… /* file contents */#endif /* __MYFILE_H_ */Multi-file project layoutNormally have a file main.cInclude the other .h filesHas a function int main(int argc, char** argv) {}To compile, use make/nmakecreate object files (*.o) and then link with librariesWe won’t go into make here.Where to go from here?This is not an exhaustive discussion of CRead the older notes onlineWrite some sample programs Get going on the assignment so that if you have simple C problems, we can help you solve them quickly.Look inK&R: The C Programming LanguageVisual Studio’s help
View Full Document