We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 5
C - Language
Cheat-SheetQuick and Dirty Guide to C
The single best book on C is The C Programming Language by Kernighan and Richi«
cope:
‘Code for execution goes into files with “.c" suffix.
Shared decl’s (included using #include “mylib.h") in “header files, end in *.h”
‘comments :
Characters to the right of // are not interpreted; they’re a comment.
Text between /+ and */ (possibly across lines) is commented out.
DATA TYPES:
Mame Size Description
char 1 byte an ASCII value: e.g. ‘a’ (see: man ascii)
int/long 4 bytes a signed integer: e.g. 97 or hex 0x61, oct Ox141
long long 8 bytes a longer multi-byte signed integer
float 4 bytes a floating-point (possibly fractional) value
double 8 bytes a double length float
char, int, and double are most frequently and easily used in small prograns
sizeof (double) computes the size of a double in addressable units (bytes)
Zero values represent logical false, nonzero values are logical true.
Math library (#include , compile with -lm) prefers double.
caSTING:
Preceding a primitive expression with an alternate parenthesized type converts or
“casts” value to a new value equivalent in new type
int a - (int) 3.131; //assigns a=3 without complaint
Preceding any other expression with a cast forces new type for unchanged value.
double b = 3.131
int a = *(int*)6
//interprets the double b as an integer (not necessarily 3)
STRUCTS and ARRAYS and POINTERS and ADDRESS COMPUTATION:
Structs collect several fields into a single logical type:
struct { int nj double root;) s; //s has two fields, n and root
S.root = sqrt((s.n=7)); //ref fields (N.B. double parens=>assign OK!)
Arrays indicated by right associative brackets ({]) in the type declaration
int a(10}; //a is a 10int array. a(0) is the first element. a[9] is the last
char b(]; //in a function header, b is an array of chars with unknown length
int ¢[2](3]: //c is an array of 2 arrays of three ints. a(1}[0] follows a[0](2}
Array variables (e.g. a,b,c above) cannot be made to point to other arrays
Strings are represented as character arrays terminated by ASCIT zero.
Pointers are indicated by left associative asterisk (*) in the type declarations:
int ata; —// a is a pointer to an integer
char *b; —// b is a pointer to a character
int *c(2]; // ¢ is an array of two pointers to ints (same as int *(c(2])+
int (*d)(2}; // d is a pointer to an array of 2 integers
Pointers are simply addre: Pointer variables may be assigned.
‘Adding 1 computes pointer to the next value by adding sizeof (x) for type x
General int adds to pointer (even 0 or negative values) behave in the same way
Adar’ may be computed with the ampersand (4) operator.
‘An array without an index or a struct without field computes its addre:
int a(10], b{20}; // two arrays
int *p = a; // p points to first int of array a
p= b; 77 p now points to the first int of array b
an array or pointer with an index n in square brackets returns the nth value:
int a[ 10}; 17 an array
int i= af0}; // 4 is the first element of a
i= ta; 1/ pointer dereference
7/ same as p = &a[0]
7/ same as p = p+l; same as p=ka[1}; same as p = atl
Bounds are not checked; your responsibility not to run off. Don’t assume.
An arrow (-> no spaces!) dereferences a pointer to a field:
struct { int n; double root; } {1}; //s is pointer to struct or array of 1
s->root = sqrt)s->n = 7); //s->root same as (*8).root or s{0].root
print£(“%g\n", 8->root);PUNCTIONS:
A function is a pointer to some code, parameterized by formal parameters, that
may be executed by providing actual parameters. Functions must be declared before
they are used, but code may be provided later. A sqrt function for positive n
might be declared a:
double sqrt (double n) {
double guess;
for (guess
return gues:
n/2.0; abs(n-guess*guess)>0.001; guess = (n/guess+guess)/2);
,
This function has type double (s*sqrt) (double
print£(“tg\n", sqrt(7.0)); //calls sqrt; actuals are always passed by value
Functions parameters are always passed by value. Functions must return a value.
‘The return value need not be used. Function names with parameters returns the
function pointer. Thus, an alias for sqrt may be declared:
double (*root) (double) = sqrt;
print£(“%g\n", root(7.0));
Procedures or valueless functions return ‘void’.
‘There must always be a main function that returns an int.
int main(int argc, char **argv) OR int main(int argc, char *argv[])
Program arguments may be accessed as strings through main’s array argv with arge
elements. First is the program name. Function declarations are never nested.
OPERATIONS:
+ /, 8 Arithmetic ops. /truncates on integers, ¢ is remainder.
Add or subtract 1 from i, assign result to i, return new val
Remember i, inc or decrement i, return remembered value
Logical ops. Right side of s& and || unless necessary
Bit logical ops: and, or, xor, complement.
Shift right and left: int n=10; n <<2 comput
. Assignment is an operator. Result is value B
+= -= t= etc Perform binary op on left and right, assign result to left
= {= < > <= >= Comparison operators (useful only on primitive types)
2 If-like expression: (x'2==0)?"even":"odd”
7 computing value is last: a, = b,c,d; exec’s b,c,d then a=d
STATEMENTS:
Angle brackets identify syntactic elements and don’t appear in real statements
; //semicolon indicates end of a simple statenent
break; J/quits the tightest loop or switch immediately
continues //jumps to next loop test, skipping rest of loop body
return x; //quits this function, returns x as value
{ } /{eurly-brace groups statements into 1 compound (no ;)
if () //stmt executed if cond true (nonzero)
if () else // two-way condition
while () //repeatedly execute stmt only if condition true
do while (); //note the semicolon, executes at least once
for (; ; )
switch () { //eraditional “case statement”
case : // this statement exec'd if val==expr
break; // quit this when value == expression
case : //executed if value2 = expression
case : //executed if value3 = expression
break; 17 quit
default: // if matches no other value; may be first
break; // optional (but encouraged) quit
»
KEY WORDS
unsigned before primitive type suggests unsigned operations
extern in global declaration => symbol is for external use
static in global declaration => symbol is local to this file
in local decl’n => don’t place on stack; keep value betw’n calls
typedef before declaration defines a new type name, not a new variableQuick and Dirty Guide to C
1/0 (#include
fclose(f) closes file £
getchar() read 1 char from stdin or pushback; is EOF (int -1) if none
ungetch(c) pushback char c into stdin for re-reading; don’t change c
putchar(c) write 1 char, c, to stdout
fgetc(f) getchar(), but reads from file f
ungetc(c, f) s ungetchar() but onto file f
fpute(c,f) 8 putchar(c), but onto file £
fgets(s,n, £) read string of n-1 chars to a s from f or til eof or \n
fputs(s,f) string s to f: e.g. fputs(“Hello world\n", stdout);
scant (py. ++) + args using format p (below); put &w/non-pointe:
print£(p, + args using format p (below); pass args as is
fprintt(f,p, but print to file £
fscant(f,p, but read from file f
sscanf(5,p,- but read from string s
sprintf(s,p,...) same, as printf, but to string s
feof (f) return true iff at end of file £
Formats use format characters preceded by escape %; other chars written as is>
char meaning char meaning
‘c character \n newline (control-3)
4d decimal integer ve tab (control~i)
4s string \ slash
4g general floating point “ perent
MEMORY (tinclude )
malloc(n) alloc n bytes of memory; for type Ts p = (T*)malloc(sizeof(t));
free(p) free memory pointed at p; must have been alloc'd; don’t re-free
calloc(n,s) alloc n-array size s & clear; typ: a = (T*)calloc(n, sizeof(T));
MATH (#include and link -1m; sometimes documented in man math)
‘All functions take and return double unless otherwise noted:
sin(a), cos(a), tan(a) sine, cosine, tangent of double (in radians)
asine(y),acos(x),atan(r) principle inverse of above
atan2(y,x) principal inverse of tan(y/x) in same quadrant as (x,y)
sqrt (x) root of x
1og(x) natural logarithm of x; others: 1og2(x) and 10g10(x)
exp(P) e to the power of p; others: exp2(x) and expl0(x)
pow (x,y) x to the power of y; like (expy*log(x))
ceil (x) smallest integer (returned as double) no less than x
floor (x) largest integer (returned as double) no greater than y
#include for these math functions
abs (x) absolute value of x
random( ) returns a random long
srandom(seed) seeds the random generator with a new random seed
STRINGS (Hinclude )
strien(s) return length of string; number of characters before ASCII 0
strepy(d,s) copy string s to d and return d; N.B. parameter order like =
strnepy(d,s,n) copy at most n characters of s to d and terminate; returns d
stpepy(d,s) like stropy, but returns pointer to ASCII 0 terminarot in d
stremp(s,t) compare strings s and t and return first difference; 0=> equal
strnemp(s,t,n) stop after at most n characters; needn’t be null terminated
memcpy(d,8,n) copy exactly n bytes from s to d; may fail if s overlaps 4
memmove(d,,n) (slow) copy n bytes from s to d; won't fail if s overlaps d
‘COMPILING:
gcc prog-c __# compiles prog.c into a-out run result with ./a-out
gcc =0 prog prog.c # compiles prog.c into prog; run result with ./prog
gee -9 -0 prog prog.c # as above, but allows for debuggingA GOOD FIRST PROGRAM:
#include
#include
int main(int argc, char** argv){
printf(“Hello, world.\n");
return 0;
y
‘A WORD COUNT (WC)
#include
#include
int main(int argc, char **argv){
int charCount=0, wordCount=0, lineCount=0;
int doChar=0, doWord=0, doLine=0, inWord = 0
int 7
char *fileName = 0;
FILE *f = stdil
while (argv++, --argc) {
if (1stromp(*argv,"-c")) doChar=1;
else if (!stremp(*argy,”-w")) doWord=1;
else if (1stromp(*argv,"-1")) doLine
else if (1(f = fopen((fileName = *argv), “r"))){
print£(“Usage: we (-1] [-w] (-c]\n"); return 1;
,
+
if (1(doChar || doWord || doLine)) doChar = doWord = doLine = 1;
while (EOF t= (c= fgetc(f))){
charCount++;
if (c == ‘\n‘) LineCount++;
if (tiswpace(c)) {
if (1inWord) { inWord = 1; wordcount++; }
} else { inword = 0; }
y
if (doLine) printf(“t8d”, lineCount);
if (doWord) print£(“t8d", wordCount);
if (dochar) printf (“t8d", charCount);
if (fileName) printf(“ ts”, fileName);
printf (“\n");