C Reference Card
Literals (examples) 123 -4 0xAf0C 057
Operators (decreasing precedence down and across)
substitutable parameters shown in italics Compilation
3.14159265 1.29e-23
++ — – ! * & ~ sizeof (typename) */% +-
Incr/decrement, unary minus, logical NOT, pointer deref., address-of, 1’s complement, size in bytes, cast Binary arithmetic operators
gcc –flags program.c
dcc –flags program.c (CSE labs only)
′′hello′′ ′′abc\′′\n′′ ′′′′ strings (char *) Character and string escapes
<< >>
< <= > >= ==!= & ^| &&||?: = += -= *= /= %= etc ,
Bitwise left shift/right shift
Relational operators
(In)equality operators; bitwise AND Bitwise exclusive OR, inclusive OR Logical AND and OR; conditional Assignment (with optional arithmetic operation)
–c
Compile only, output to file.o Executable output to file Generate debugging info for gdb
symbol
represents symbol
represents
–o file –g
\t tab \ddd \n newline \ ́ \r carriage-return \′′ \0 null character \\
ASCII value (octal) single quote double quote backslash
–Wall Turnonallwarnings
Lexical structure, preprocessor
Declarations (examples)
Comma (sequential) operator Left-associative except for (right associative)
/* comment */
// comment to end of line
int i, length;
char *str, buf[BUFSIZ], prev;
double x, values[MAX];
Statements
#include
#define NAME replacement-text #define NAME(args…) replacement-text
typedef enum { FALSE, TRUE } Bool;
expression ;
{ statements… }
if (expression) statement
if (expression) statement else statement
Program structure:
type funcname(type param1, type param2 …);
Header files: declarations only (#includes, #defines, function prototypes)
More types
Implementation files: #includes, #defines, prototypes for local functions, function definitions
short (int) long (int, double)
unsigned (int, char)
}while(expression) statement
for (initialiser; condition; increment) statement do statement while(expression);
Main program file: as for implementation, must have main: int main(int argc, char **argv)
Storage classes (common)
static local to file, or var saved across function calls
Identifiers start with a letter, followed by any number of letters, digits or underscores
int c=0;
char prev = ́\n ́;
char *mssg = ′′hello′′;
int seq[MAX]={1,2,3}; KeyValType keylist[] = {
break;
continue;
return expr;
goto identifier; transfer to label (rare)
Identifiers starting with _ reserved for system use
Reserved words (can’t use as identifiers):
auto break case char const continue default do double else entry enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
′′NSW′′, 0, ′′Vic′′, 5 , ′′Qld′′, -1 };
2004-06-21
integers (int) reals (double) characters (char)
() [] . ->
Brackets, array, struct, pointer-struct
́x ́ ́\t ́ ́\033 ́
typedef struct {
char *key;
int val;
} KeyValType;
switch(expression) {
case constant : statements…break; case constant : statements…break; default : statements
extern accessible everywhere Initialisation (examples)
terminate loop or switch resume next iteration of loop return value from function
C library functions (and other objects) Parameternameimpliestype: c char
ctype.h
Common programming patterns
n int l long s string (char *)
int c;
b buffer (char array) d double fh
p pointer (void *) file handle (FILE *)
while ((c = getchar()) != EOF) { putchar(c); // or some other use of c
stdlib.h
string.h
}
atoi(s) atof(s) malloc(n) calloc(n) free(p)
exit(n)
string to int or double allocate n bytes
recycle memory
terminate with status n absolute value
strlen(s)
length (excluding ́\0 ́) copy ss to sd, return sd append ss to sd, return sd compare, return <0 ==0 >0
Read input a line at a time:
abs(n) labs(l)
while(fgets(buf,BUFSIZ,stdin) != NULL)
process_line(buf);
stdio.h
strncpy(sd,ss,n) strncat(sd,ss,n) strncmp(s1,s2,n) max n chars processed
Opening a file named on the command line:
stdin stdout stderr FILE * variables BUFSIZ EOF NULL constants
strchr(s,c)
strrchr(s,c)
strstr(s,sp)
strpbrk(s,set)
return ptr to first c in s
return ptr to last c in s
return ptr to first sp in s return ptr to first of any in set
FILE *fp;
fopen(s,mode) open file, returns fh mode is one or more of ′′r′′, ′′w′′, ′′a′′ ′′b′′ ′′+′′
fp = fopen(argv[1], ′′r′′);
if (fp == NULL) {
fclose(fh)
fgetc(fh) getchar()
fgets(b,n,fh)
fputc(c,fh) putchar(c)
fputs(s,fh)
fread(p,size,nel,fh)
close file
read char, EOF if none read line, NULL if none write char
write line
read into binary buffer,
strspn(s,set)
strcspn(s,set)
length of prefix of any in set length of prefix all not in set
fprintf(stderr, ′′can’t open %s\n′′,
exit(1); argv[1]);
fwrite(p,size,nel,fh)
return number of elements read write from binary buffer
atan2(y,x)
sinh(d) cosh(d) tanh(d)
exp(d) log(d) log10(d)
pow(x,y) sqrt(d)
floor(d) ceil(d)
= tan 1(y/x) hyperbolic exponential, logarithm xy, square root integral bounds
else {
// open fp as above
Formatted output:
process(fp);
}
fprintf(fh, format, list) printf(format, list) sprintf(b, format, list)
formatted output to fh fmt output to stdout formatted output to string
Print array of real numbers:
formatitems %width.precisioncode negative width left-justifies. code is one of
fabs(d) fmod(x,y)
absolute value, x % y
for (i=0; i < MAX; i++)
printf(′′%14.6f\n′′, sample[i]);
d decimal o octal
f fixed point g general c character s string % literal ́% ́ character
x hexadecimal
e exponential (scientific) p pointer
Function to find the length of a string:
Formatted input:
char *sp;
fscanf(fh, format, list) scanf(format, list) sscanf(s, format, list)
formatted input from fh fmt input from stdin formatted input from string
for (sp=s; *sp != ́\0 ́; sp++)
len++;
format codes similar to printf, list has addresses
return len; }
toupper(c)
isupper(c)
isalpha(c)
isdigit(c)
isspace(c)
tolower(c)
islower(c)
isalnum(c)
isxdigit(c)
isprint(c)
case mapping
case testing alpha(betic|numeric) decimal or hex digit white space, printable
Read input a character at a time:
strcpy(sd,ss)
strcat(sd,ss)
strcmp(s1,s2)
char buf[BUFSIZ];
math.h (all parameters are double)
Same, but file name is optional, default standard input:
sin(d) cos(d) tan(d)
asin(d) acos(d) atan(d)
trigonometry (radians) inverse (radians)
if (argc == 1)
process(stdin);
−
}
int mystrlen(char *s)
{
int len=0;