From C++ to Java A whirlwind tour of Java for C++ programmers.
C For Java Programmers
description
Transcript of C For Java Programmers
C For Java Programmers
Tom Roeder
CS415 2005sp
Why C?
The language of low-level systems programming Commonly used (legacy code) Trades off safety for speed Clear mapping from C statements to operations
Simple to understand, imperative language Well-understood common optimizations
Why not C?
Explicit memory management Memory leaks Invalid pointers
No (built-in) exception handling Not type safe Poor separation of concerns
No good language support for modularization Too close to assembly
Common Constructs in C and Java Loops
if() {} for(;;) {} while() {} do {} while()
Functions int call_me(float a) {return (int)a;} int temp = call_me(3.14);
C Types: Primitives
Often architecture-dependent int, short, long
Can count on short <= int <= long float, double
Can usually count on float <= double char
One byte per character Unicode WCHAR in Windows: two bytes
C Types: struct
Often need to define object-like storage units C only encapsulates data, not methods struct is the unit of encapsulation
struct pos {float x;float y;
} p;p.x = 0.7;
p.y = 0.1;
C Types: enum
When you need to write code like
Color x = RED; enum { BLUE, RED, GREEN }; We’ll get to how to define the Color symbol enums are actually underlying ints.
Can have any value at all enum { BLUE = 7, RED = 137, GREEN }; GREEN will have value 138.
C Types: pointers
A pointer contains the starting address of the memory for a given value
int 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 strings
An 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 characters
int 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: typedef
When 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* INTP
C Types: void*
void* is a pointer to any type Extremely useful in generic data structurestypedef struct queue_t {
void* elt;
queue_t* next;
} queue;
queue* q;
…
*(int*)(q->elt) = 137;
C Functions: function pointers Unlike in Java, we don’t have any reflection We 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 function
C Functions: parameter passing Two methods in C
By value By reference
int 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
reference
C Functions: prototypes
A function in C must be declared before used Thus 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 management Don’t forgot to free memory you’ve alloc’ed Arrays are not bounds checked in C Set all pointers to NULL
when they are initialized when they are freed
Requires strict discipline, and you will forget Use Purify (if on *NIX, use valgrind) Always check to see if a pointer is NULL before
using it.
C Traps: local variables
Simple 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 Preprocessor
Used for constants and simple replacements#define PI 3.14#define DEBUG 1
Also used for macros with arguments#define max(x,y) ((x)>=(y) ? (x):(y))
Conditional compilation#if DEBUG#endif
includes: #include <stdio.h>
Most Common C Libraries
<stdio.h> : standard I/O printf (format, …); printf(“Hello there, %s\n”, “Tom”);
%s – strings %c – characters %d – integers %f – float %lf – double
<stdlib.h>: useful functions: exit, malloc, free
Multi-file project layout
Divide the code into functional units Each unit has a .h and a .c file Put the prototypes in the .h and the functions in .c
To 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 layout
Normally have a file main.c Include the other .h files Has a function int main(int argc, char** argv) {}
To compile, use make/nmake create object files (*.o) and then link with libraries We won’t go into make here.
Where to go from here?
This is not an exhaustive discussion of C Read the older notes online Write some sample programs Get going on
the assignment so that if you have simple C problems, we can help you solve them quickly.
Look in K&R: The C Programming Language Visual Studio’s help facility