a late-in-season picking of finest bytes
have been brought together to produce this boutique
— C reference card —
Compilation
gcc flags file.c
-c compile only, default output file.o
Statements
expression;
if (condition) statement [else statement]
Declarations
int i, length;
char *str, buf[BUFSIZ], prev;
double x, values[MAX];
typedef enum { FALSE, TRUE } Bool;
typedef struct { char *key; int val; } keyval t;
Initialisation
int c = 0;
char prev = ‘\n’;
char *msg = “hello”;
int seq[MAX] = { 1, 2, 3 }; keyval t keylist[] = {
“NSW”, 0, “Vic”, 5, “Qld”, -1 }; Character & String Escapes
-o out
output to out
while (condition) statement
for (initialiser; condition; increment) statement do statement while (condition);
break; terminate loop or switch
continue; resume next iteration of loop
return [value]; return (optional) value from function
Lexical Structure & Preprocessor
/* a comment, maybe over multiple lines */
// a comment to the end of the line
#include
#define symbol replacement-text
.h files: #defines, typedefs, function prototypes
.c files: #defines, structs, statics, function definitions; optionally also int main (int argc, char *argv[])
Identifiers start with a letter, followed by letters, digits, or underscores. Identifiers starting with ‘ ’ are reserved for system use. The following words are also reserved:
auto break case char const continue default do double else enum extern float for goto if inline int long register restrict return short signed sizeof static struct switch typedef union unsigned void volatile while
Bool Complex Imaginary
Type Qualifiers
goto label;
transfer to label (EVIL)
Operators
accessible everywhere
extern
static
const
restrict function will use this pointer-type argument inline function should be inlined at call
file-local; value saved across function calls can’t/won’t change volatile likely to change
integers (int):
reals (float/double): characters (char): strings (char *):
switch (condition) {
case constant : statements… [ default: statements…]
}
break;
* < & && = ,
bitwise-and logical-and
+= -= *=
| bitwise-or ˆ bitwise-xor || logical-or ?: ternary
decreasing precedence downwards left-to-right operators are left-associative
except cast, ternary, assignment
\n line feed (“newline”) \t horizontal tab
\' single quote
\\ backslash
\ddd octal ascii value
carriage return \r escape \e double quote \" null character \0 hex ascii value \xdd
()
.
++
!
̃
(type) cast to type
[v ]
-> struct*’s field (‘arrow’, ‘stab’)
brackets struct field
v th increment — decrement + value-of – negate
* dereference (‘value-at’)
& reference (‘address-of’) sizeof(type) #bytes of type / % + – arithmetic << >> left/rightbitshift <= > >= relational operators == != (in)equality
logical-not bitwise-not
sequential comma
/=
%=
(arithmetic on) assignment
Literals
123 -4 0xAf0C 057 3.14159265 1.29e-23 ‘x’ ‘t’ ‘\033’ “hello” “abc\”\n” “”
{ statements… }
index
The C Standard Library
only a limited, ‘interesting’ subset is listed here. type modifiers, notably const, have been omitted. consult the relevant man(1) or info(1) pages.
// in stdlib.h
#define NULL ((void *)0) void *malloc (size t size);
void *calloc (size t number, size t size); allocate size or (number * size) bytes. calloc initialises allocated space to zero.
void free(void *obj);
release allocated pointer obj, no-op if NULL.
void exit(int status); void abort(); terminate the current program (ab)normally.
returns status to the os or sends SIGABRT.
int atoi(char *str);
long strtol(char *str, char **end, int base);
converts string str to a (long) int value. strtol supports radix 2 ≤ base ≤ 36; references first invalid char in end if non-NULL.
double atof(char *str);
double strtod(char *str, char **end);
converts string str to a double.
first invalid character address in end if non-NULL.
// in stdio.h
// in string.h
int abs (int x); returns |x|
// in ctype.h
long labs (long x);
int
int
int
…);
int toupper(int c);
make ascii c uppercase or lowercase
double log(double x);
int isupper (int c); int isalpha (int c); int isdigit (int c); int isspace (int c);
int int int
double
double
pow (double x, double y); sqrt (double x);
returns xy returns √x ceil (double x);
returns |x| returns x mod y
is ascii c upper/lowercase, alphabetic, alphanumeric, a digit, a hex digit, whitespace, or printable?
double
int tolower(int c); int islower (int c);
int isalnum (int c); int isxdigit (int c); int isprint (int c);
returns tan−1 y x
double exp(double x); returns exp, loge of x
#define EOF (-1)
special ‘end-of-file’ return value
FILE *stdin, *stdout, *stderr; standard input/output/error
FILE *fopen(char *filename, char *mode); open file; return new ‘file handle’.
size t strlen (char *str);
the length of str without trailing nul.
char *strcpy(char *dst, char *src); char *strcat(char *dst, char *src);
copy or concatenate src onto dst until nul or sz int strcmp(char *s1, char *s2);
return < 0,= 0,> 0 if s1 <,=,> s2
char *strchr(char *str, int c); char *strrchr(char *str, int c);
find first/last instance of c in str, or NULL char *strstr (char *haystack, char *needle);
find first instance of string needle in haystack char *strpbrk(char *str, char *any);
find first of any of any in str.
size t strspn (char *str, char *any);
size t strcspn (char *str, char *any); length of prefix of any of any (not) in str
char *strsep(char **strp, char *sep);
find first of any of sep in *strp, writes nul returns original *strp, byte after sep in strp replaces old strtok
// in math.h
// remember to compile and link -lm
int int
fclose(FILE *fh);
close a file; returns non-zero on error.
fgetc(FILE *fh); int getchar(void); return next character from fh, or EOF on eof/error. getchar equivalent to fgetc (stdin)
char *fgets(char *s, int size, FILE *fh); read into s until eof, newline, or size bytes. returns s, or NULL on error.
int
int int
c);
fputc (int c, FILE *fh); int write c to fh; returns EOF on error. putchar (k ) equivalent to fputc (k ,
fputs(char *str, FILE *fh);
puts(char *str);
write str to fh; returns EOF on error.
puts (k) equivalent to fputs (k “\n”, stdout)
printf(char *fmt, …);
fprintf(FILE *fh, char *fmt, …); snprintf (char *buf, size tlen, char *fmt,
print text per fmt to stdout, fh or buf.
formatting commands: “%m w.p c”
field width in w; < 0 left-justifies; decimal places in p. code in c: decimal, octal, hexadecimal, char, string,
f ixed-point, general, exp., pointer, literal size in m: long [long]; short [short], size t, ptrdiff t. arguments with matching types follow fmt
returns number of characters written, or EOF on error
scanf(char *fmt, ...);
fscanf(FILE *fh, char *fmt, ...); sscanf(char *str, char *fmt, ...);
parse text from stdout, fh or str per fmt.
fmt is not exactly the same as printf formats. pointer arguments with matching types follow fmt returns number of fields matched, or -1 on error
double
double
double
sin (double x); cos (double x); tan (double x);
double
double
double
asin (double x); acos (double x); atan (double x);
putchar (int stdout)
%
returns sin, sin−1, cos, cos−1, tan, tan−1 of x double atan2(double y, double x);
floor (double x); returns ⌊x⌋ and ⌈x⌉
double
double fabs (double x);
double fmod (double x, double y);