0% found this document useful (0 votes)
36 views22 pages

Ashlyn Black - C Reference

This document provides a cheat sheet reference for C programming. It covers topics like number literals, variables, data types, typecasting, and structures.

Uploaded by

Pas DEN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views22 pages

Ashlyn Black - C Reference

This document provides a cheat sheet reference for C programming. It covers topics like number literals, variables, data types, typecasting, and structures.

Uploaded by

Pas DEN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

C Reference Cheat Sheet

by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Number Literals Variables (cont)

Integers const int x = 88; A constant variable: can't assign to


0b11111111 binary 0B11111111 binary after declar​ation (compiler enforced.)

0377 octal 255 decimal Naming

johnny5IsAlive;  Alphanumeric, not a keyword, begins


0xff hexadecimal 0xFF hexadecimal
with a letter.
Real Numbers
2001ASpaceOddysey;  Doesn't begin with a letter.
88.0f / 88.1234567f
while;  Reserved keyword.
single precision float ( f suffix )
how exciting!;  Non-alphanumeric.
88.0 / 88.123456789012345
iamave​ryl​ong​var​iab​len​ame​ohm​ygo​shy​esiam;
double precision float ( no f suffix )

Signage
Longer than 31 characters (C89 & C90 only)
42 / +42 positive -42 negative
Constants are CAPITALISED. Function names usually take the form
Binary notation 0b... / 0B... is available on GCC and most but not of a verb eg. plotRobotUprising().
all C compilers.
Primitive Variable Types
Variables
*applicable but not limited to most ARM, AVR, x86 & x64
Declaring installations
int x; A variable. [class] [qualifier] [unsigned] type/void name;
char x = 'C'; A variable & initialising it. by ascending arithmetic conversion
float x, y, z; Multiple variables of the same type. Integers
Type Bytes Value Range

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 1 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Primitive Variable Types (cont) Primitive Variable Types (cont)

char 1 unsigned OR signed long long 8 unsigned OR signed


8
unsigned char 1 0 to 2 -1 unsigned long long 8 0 to 264-1

signed char 1 -27 to 27-1 signed long long 8 -263 to 263-1

int 2/4 unsigned OR signed Floats


16 31 Type Bytes Value Range (Norma​lized)
unsigned int 2/4 0 to 2 -1 OR 2 -1

signed int 2/4 -215 to 215-1 OR -231 to 232-1 float 4 ±1.2×10-38 to ±3.4×1038

short 2 unsigned OR signed double 8/4 ±2.3×10-308 to ±1.7×10308 OR


alias to float for AVR.
unsigned short 2 0 to 216-1
long double ARM: 8, AVR: 4, x86: 10, x64: 16
signed short 2 -215 to 215-1
Qualifiers
long 4/8 unsigned OR signed
const type Flags variable as read-only (compiler can
unsigned long 4/8 0 to 232-1 OR 264-1
optimise.)
signed long 4/8 -231 to 231-1 OR -263 to 263-1

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 2 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Primitive Variable Types (cont) Primitive Variable Types (cont)

volatile type Flags variable as unpredictable (compiler char x = 1, y = 2; float z = (float) x / y;


cannot optimise.)
Some types (denoted with OR) are architecture dependant.
Storage Classes
register Quick access required. May be stored in RAM There is no primitive boolean type, only zero (false, 0) and non-zero
OR a register. Maximum size is register size. (true, usually 1.)
static Retained when out of scope. static global
variables are confined to the scope of the Extended Variable Types
compiled object file they were declared in. [class] [quali​fier] type name;
extern Variable is declared by another file. by ascending arithmetic conversion
Typecasting From the stdint.h Library
(type)a Returns a as data type. Type Bytes Value Range
int8_t 1 -27 to 27-1

uint8_t 1 0 to 28-1

int16_t 2 -215 to 215-1

uint16_t 2 0 to 216-1

int32_t 4 -231 to 231-1

uint32_t 4 0 to 232-1

int64_t 8 -263 to 263-1

uint64_t 8 0 to 264-1

From the stdbool.h Library

Type Bytes Value Range

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 3 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Extended Variable Types (cont) Structures (cont)

bool 1 true / false or 0 / 1 struct strctName varName = { a, b }; A variable varN


ame as
The stdint.h library was introduced in C99 to give integer types
structure type s
archit​ect​ure​-in​dep​endent lengths.
trctName and

Structures initialising its


members.
Defining
Accessing
struct strctName{ type x; type y; }; A structure
varName.x Member x of
type strct
structure varNa
Name with
me.
two
members, xptrName->x Value of
and y. Note structure pointer
trailing ptrName
semicolon member x.

struct item{ struct item *next; }; A structure Bit Fields


with a struct{char a:4, b:4} x; Declares x with
recursive two members a
structure and b, both four
pointer
bits in size (0 to
inside.
15.)
Useful for
Array members can't be assigned bit fields.
linked lists.
Declaring
Type Defini​tions
struct strctName varName; A variable v
Defining
arName as
typedef unsigned short uint16; Abbreviating
structure
a longer
type strct
type name
Name.
to uint16
struct strctName *ptrName; A strctNa
typedef struct structName{int a, b;}newType; Creating a
me structure
ewType
type pointer,
from a
ptrName.
structure.
struct strctName{ type a; type b; } varName; Shorthand
for defining
strctName
and
declaring va
rName as
that
structure
type.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 4 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Type Defini​tions (cont) Enumer​ation

typedef enum typeName{false, true}bool; Creating an Defining


enumerated enum bool { false, true }; A custom data type bool with
bool type. two possible states: false or
Declaring true.
uint16 x = 65535; Variable x Declaring
as type uin enum bool varName; A variable varName of data
t16. type bool.
newType y = {0, 0}; Structure y Assigning
as type new
varName = true; Variable varName can only be
Type.
assigned values of either fal
se or true.
Unions
Evaluating
Defining
if(varName == false) Testing the value of varName.
union uName{int x; char y[8];} A union type uName with
two members, x & y.
Pointers
Size is same as biggest
Declaring
member size.
type *x; Pointers have a data type like normal variables.
Declaring
union uN vName; A variable vName as void *v; They can also have an incomplete type. Operators
other than assignment cannot be applied as the length
union type uN.
of the type is unknown.
Accessing
vName.y[int] Members cannot store
values concur​rently.
Setting y will corrupt x.

Unions are used for storing multiple data types in the same area of
memory.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 5 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Pointers (cont) Arrays (cont)

struct type *y; A data structure pointer. type name[int] = {x}; You set array length

type z[]; An array/​string name can be used as a and initialise all

pointer to the first array element. elements to x.

Accessing type name[] = {x, y, z}; Compiler sets array


length based on
x A memory address.
initial elements.
*x Value stored at that address.
Size cannot be changed after declaration.
y->a Value stored in structure pointer y member
Dimensions
a.
name[int] One dimension
&varName Memory address of normal variable varNam
array.
e.
name[int][int] Two dimens​ional
*(type *)v Dereferencing a void pointer as a type array.
pointer.
Accessing
A pointer is a variable that holds a memory location. name[int] Value of element in
t in array name.
Arrays
*(name + int) Same as name[int
Declaring
].
type name[int]; You set array length.
Elements are contiguously numbered ascending from 0 .
type name[int] = {x, y, z}; You set array length and
&name[int] Memory address of
initialise elements.
element int in array
name.

name + int Same as &n​ame​[


int].

Elements are stored in contiguous memory.


Measuring
sizeof(array) / sizeof(arrayType) Returns length of ar
ray. (Unsafe)

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 6 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Arrays (cont) Escape Characters (cont)

sizeof(array) / sizeof(array[0]) Returns length of arr \? question mark


ay. (Safe) \nnn Any octal ANSI character code.

\xhh Any hexadecimal ANSI character code.


Strings

'A' character Single quotes. Functions


"AB" string Double quotes. Declaring
\0 Null termin​ator. type/void funcName([args...]){ [return var;] }
Strings are char arrays. Function names follow the same restrictions as variable names but
char name[4] = "Ash"; must also be unique.

is equivalent to type/void Return value type (void if none.)

char name[4] = {'A', 's', 'h', '\0'}; funcName() Function name and argument parenthesis.

int i; for(i = 0; name[i]; i++){} args... Argument types & names (void if none.)

\0 evaluates as false. {} Function content delimi​ters.

Strings must include a char element for \0.

Escape Characters

\a alarm (bell/beep) \b backspace

\f formfeed \n newline

\r carriage return \t horizontal tab

\v vertical tab \\ backslash

\' single quote \" double quote

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 7 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Functions (cont) Functions (cont)

return var; Value to return to type f(){ static type x[]; return &x; } Returning an
function call origin. Skip array/string/structure
for void type functions. by pointer. The
Functions exit tic qualifier is
immediately after a ret necessary otherwise
urn. x won't exist after

By Value vs By Pointer the function exits.

void f(type x); f(y); Passing variable y to Passing by pointer allows you to change the originating variable within the

function f argument x function.

(by value.) Scope

void f(type *x); f(array); Passing an array/string int f(){ int i = 0; } i++; 
to function f argument x i is declared inside f(), it doesn't exist outside that function.
(by pointer.)
Prototyping
void f(type *x); f(structure); Passing a structure to
type funcName(args...);
function f argument x
Place before declaring or referencing respective function (usually before
(by pointer.)
n .)
void f(type *x); f(&y); Passing variable y to
type funcName([args...]) Same type, name
function f argument x
and args... as
(by pointer.)
respective function.
type f(){ return x; } Returning by value.
; Semicolon instead of
type f(){ type x; return &x; } Returning a variable by
function delimiters.
pointer.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 8 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

main() Condit​ional (Branc​hing) (cont)

int main(int argc, char *argv[]){return int;} if(a){ b; }else if(c){ d; }else{ e; }

Anatomy
int main Program entry point.

int argc # of command line arguments.

char *argv[] Command line arguments in an array of strings.


#1 is always the program filename.
return int; Exit status (integer) returned to the OS upon
program exit. switch, case, break
Command Line Arguments switch(a){ case b: c; }
app two 3 Three arguments, "​app​", "​two​" and "​3".

app "two 3" Two arguments, "​app​" and "two 3".


switch(a){ default: b; }
main is the first function called when the program executes.

Condit​ional (Branc​hing)

if, else if, else


if(a) b; Evaluates b if a is true. switch(a){ case b: case c: d; }
if(a){ b; c; } Evaluates b and c if a is true.

if(a){ b; }else{ c; } Evaluates b if a is true, c otherwise.

switch(a){ case b: c; case d: e; default: f; }

switch(a){ case b: c; break; case d: e; break; default: f;

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 9 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Iterative (Looping) Iterative (Looping) (cont)

while OR
int x = 0; while(x < 10){ x += 2; } for(int i = 0; n[i] != '\0'; i++){} (C99+)

Loop skipped if test condition initially false. Compact increment/decrement based loop.
int x = 0; Declare and initialise integer x. int i; Declares integer i.

while() Loop keyword and condition parenthesis. for() Loop keyword.

x < 10 Test condition. i = 0; Initialises integer i. Semicolon.

{} Loop delimiters. n[i] != '\0'; Test condition. Semicolon.

x += 2; Loop contents. i++ Increments i. No semicolon.

do while {} Loop delimiters.


char c = 'A'; do { c++; } while(c != 'Z'); continue
Always runs through loop at least once. int i=0; while(i<10){ i++; continue; i--;}
char c = 'A'; Declare and initialise character c. Skips rest of loop contents and restarts at the beginning of the loop.
do Loop keyword. break

{} Loop delimiters. int i=0; while(1){ if(x==10){break;} i++; }

c++; Loop contents. Skips rest of loop contents and exits loop.

while(); Loop keyword and condition parenthesis. Note


semicolon.
c != 'Z' Test condition.

for
int i; for(i = 0; n[i] != '\0'; i++){} (C89)

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 10 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Console Input/​Output Console Input/​Output (cont)

#include <stdio.h> scanf("%d", &x) Read value/s (type

Characters defined by format


string) into variable/s
getchar() Returns a single
(type must match)
character's ANSI code
from the input stream.
from the input stream
Stops reading at the
buffer as an integer .
first whitespace. &
(safe)
prefix not required for
putchar(int) Prints a single character
arrays (including
from an ANSI code
strings.) (unsafe)
integer to the output
printf​("I love %c %d!", 'C', 99 Prints data (formats
stream buffer.
) defined by the format
Strings
string) as a string to
gets(strName) Reads a line from the the output stream.
input stream into a string
Alternative
variable. (Unsafe,
removed in C11.)
Alternative

fgets(strName, length, stdin); Reads a line from the


input stream into a string
variable. (Safe)
puts("string") Prints a string to the
output stream.
Formatted Data

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 11 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Console Input/​Output (cont) File Input/​Output (cont)

fgets(strName, length, stdin); sscanf(strName, "%d", &x); Uses fg


filename String containing file's directory path & name.

modeets to String specifying the file access mode.


limit the
Modes
input
"r" / "rb" Read existing text/binary file.
length,
"w" /then
"wb" Write new/over existing text/binary file.

"a" /uses
"ab"ss Write new/append to existing text/binary file.
canf to
"r+" / "r+b" / "r Read and write existing text/binary file.
read the
b+"
resulting
/ "w+b"
"w+"string in / "w Read and write new/over existing text/binary
b+" place of file.

/ "a+b" / "a
"a+"scanf. Read and write new/append to existing
b+" (safe) text/binary file.

The stream buffers must be flushed to reflect changes. String Closing


terminator characters can flush the output while newline characters
can flush the input.

Safe functions are those that let you specify the length of the input.
Unsafe functions do not, and carry the risk of memory overflow.

File Input/​Output

#include <stdio.h>

Opening
FILE *fptr = fopen(filename, mode);

FILE *fptr Declares fptr as a FILE type pointer (stores


stream location instead of memory location.)
fopen() Returns a stream location pointer if successful, 0
otherwise.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 12 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

File Input/​Output (cont) File Input/​Output (cont)

fclose(fptr); Flushes buffers and fgetc(fptr) Returns character read or


closes stream. Returns 0 EOF if unsucc​essful. (safe)
if successful, EOF fputc(int c, fptr) Returns character written or
otherwise. EOF if unsucc​essful.
Random Access Strings
ftell(fptr) Return current file fgets(char *s, int n, fptr) Reads n-1 characters from
position as a long file fptr into string s.
integer. Stops at EOF and \n. (safe)
fseek(fptr, offset, origin); Sets current file position. fputs(char *s, fptr) Writes string s to file fptr.
Returns false is
Returns non-ne​gative on
successful, true
success, EOF otherwise.
otherwise. The offset
Formatted Data
is a long integer type.
fscanf(fptr, format, [...]) Same as scanf with
Origins
additional file pointer
SEEK_SET Beginning of file.
parameter. (unsafe)
SEEK_CUR Current position in file.
fprintf(fptr, format, [...]) Same as printf with
SEEK_END End of file. additional file pointer
Utilities parameter.

feof(fptr) Tests end-of-file Alternative


indicator.
rename(strOldName, strNewName) Renames a file.

remove(strName) Deletes a file.

Characters

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 13 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

File Input/​Output (cont) Placeh​older Types (f/printf And f/scanf) (cont)

fgets(strName, length, fptr); sscanf(strName, "%d", &x);%u Uses fge 42 Unsigned decimal integer.

%o ts to limit 52 Unsigned octal integer.


the input
%x or %X 2a or 2A Unsigned hexadecimal
length,
integer.
then uses
%f or %F 1.21 Signed decimal float.
sscanf to
%e or %E the 1.21e+9 or 1.21E+9
read Signed decimal w/ scientific
resulting notation.
string
%g or %G in 1.21e+9 or 1.21E+9 Shortest representation of
place of s %f/%F or %e/%E.
canf.
%a or %A 0x1.207c8ap+30 or 0X1 Signed hexadecimal float.
(safe)
.207C8AP+30
Binary
%c a A character.
fread(void *ptr, sizeof(element), number, fptr) Reads a n
%s A String. A character string.
umber of
%p A pointer.
elements
%% from fptr % A percent character.
to array *
ptr.
(safe)
fwrite(void *ptr, sizeof(element), number, fptr) Writes a n
umber of
elements
to file fpt
r from
array *pt
r.

Safe functions are those that let you specify the length of the input.
Unsafe functions do not, and carry the risk of memory overflow.

Placeh​older Types (f/printf And f/scanf)

printf("%d%d...", arg1, arg2...);

Type Example Descri​ption


%d or %i -42 Signed decimal integer.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 14 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Placeh​older Types (f/printf And f/scanf) (cont) Placeh​older Formatting (f/printf And f/scanf) (cont)

%n No output, saves # of characters printed so far. Respective Precision


printf argument must be an integer pointer. .integer Minimum # of digits to print for %d, %i, %o, %u, %x, %X.
The pointer format is architecture and implementation dependant. Left pads with zeroes. Will not truncate. Skips values
of 0.
Placeh​older Formatting (f/printf And f/scanf) Minimum # of digits to print after decimal point for %a,
%[Flags][Width][.Precision][Length]Type %A, %e, %E, %f, %F (default of 6.)

Flags Minimum # of significant digits to print for %g & %G.

- Left justify instead of default right justify. Maximum # of characters to print from %s (a string.)

+ Sign for both positive numbers and negative. . If no integer is given, default of 0.

# Precede with 0, 0x or 0X for %o, %x and %X tokens. .* Precision specified by a preceding argument in print

space Left pad with spaces. f.

0 Left pad with zeroes. Length


hh Display a char as int.
Width
integer Minimum number of characters to print: invokes padding h Display a short as int.

if necessary. Will not truncate. l Display a long integer.


* Width specified by a preceding argument in printf. ll Display a long long integer.

L Display a long double float.

z Display a size_t integer.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 15 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Placeh​older Formatting (f/printf And f/scanf) (cont) C Reserved Keywords

j Display a intmax_t integer. _Alignas break float signed

t Display a ptrdiff_t integer. _Alignof case for sizeof

_Atomic char goto static


Prepro​cessor Directives
_Bool const if struct
#include <inbuilt.h> Replaces line with contents of a
_Complex continue inline switch
standard C header file.
_Generic default int typedef
#include "./custom.h" Replaces line with contents of a
custom header file. Note dir path _Imaginary do long union
prefix & quotations. _Noreturn double register unsigned
#define NAME value Replaces all occurrences of NAME _Static_assert else restrict void
with value.
_Thread_local enum return volatile

auto extern short while


Comments
_A-Z... __...
// We're single-line comments!
// Nothing compiled after // on these lines.
C / POSIX Reserved Keywords
/* I'm a multi-line comment!
​ ​ ​Nothing compiled between E[0-9]... E[A-Z]... is[a-z]... to[a-z]...

​ ​ ​these delimi​ters. */ LC_[A-Z]... SIG[A-Z]... SIG_[A-Z]... str[a-z]...

mem[a-z]... wcs[a-z]... ..._t

GNU Reserved Names

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 16 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Header Reserved Keywords Header Reserved Keywords (cont)

Name Reserved By Library GNU Reserved Names


d_... dirent.h
Heap Space
l_... fcntl.h
#include <stdlib.h>
F_... fcntl.h
Allocating
O_... fcntl.h
malloc(); Returns a
S_... fcntl.h
memory
gr_... grp.h location if
..._MAX limits.h succes​sful
NULL
pw_... pwd.h
otherwise.
sa_... signal.h
type *x; x = malloc(sizeof(type)); Memory fo
SA_... signal.h
a variable.
st_... sys/stat.h
type *y; y = malloc(sizeof(type) * length ); Memory fo
S_... sys/stat.h an
tms_... sys/times.h array/string

c_... termios.h struct type *z; z = malloc(sizeof(struct type)); Memory fo


a structure
V... termios.h
Deallocating
I... termios.h
free(ptrName); Removes
O... termios.h
the memor
TC... termios.h allocated t
B[0-9]... termios.h ptrName

Reallocating

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 17 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Heap Space (cont) The Standard Library (cont)

realloc(ptrName, size); Attempts to resize the memory Sorting


block assigned to ptrName. qsort(array, length, sizeof(type), compFu
The memory addresses you see are from virtual memory the qsort() Sort using the QuickSort algorithm
operating system assigns to the program; they are not physical
array Array/string name.
addresses.
length Length of the array/string.

Referencing memory that isn't assigned to the program will produce sizeof(type) Byte size of each element.
an OS segmentation fault. compFunc Comparison function name.

compFunc
The Standard Library
int compFunc( const void *a, const void b* ){ return( *(in
#include <stdlib.h>
int compFunc() Function name unimportant but m
Random​icity
const void *a, const void *b Argument names unimportant but
rand() Returns a (predictable) random
integer between 0 and return( *(int *)a - *(int *)b); Negative result swaps b for

RAND_MAX based on the result of 0 doesn't swap.


randomiser seed. C's inbuilt randomiser is cryptographically insecure: DO NOT use it
RAND_MAX The maximum value rand() can for security applications.
generate.
srand(unsigned integer); Seeds the randomiser with a
positive integer.
(unsigned) time(NULL) Returns the computer's tick-tock
value. Updates every second.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 18 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

The Character Type Library The String Library

#include <ctype.h> #include <string.h>

tolower(char) Lowercase char. strlen(a) Returns # of char in string a as an integer.

toupper(char) Uppercase char. Excludes \0. (unsafe)

isalpha(char) True if char is a letter of the alphabet, false strcpy(a, b) Copies strings. Copies string b over string a

otherwise. up to and including \0. (unsafe)

islower(char) True if char is a lowercase letter of the strcat(a, b) Concat​enates strings. Copies string b over
alphabet, false otherwise. string a up to and including \0, starting at
the position of \0 in string a. (unsafe)
isupper(char) True if char is an uppercase letter of the
alphabet, false otherwise. strcmp(a, b) Compares strings. Returns false if string a

isnumber(char) True if char is numerical (0 to 9) and false equals string b, true otherwise. Ignores

otherwise. characters after \0. (unsafe)

isblank True if char is a whitespace character (' ', strstr(a, b) Searches for string b inside string a.

'\t', '\n') and false otherwise. Returns a pointer if succes​sful, NULL


otherwise. (unsafe)
Alternatives
strncpy(a, b, n) Copies strings. Copies n characters from
string b over string a up to and including \0.
(safe)

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 19 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

The String Library (cont) The Time Library (cont)

strncat(a, b, n) Concat​enates strings. Copies n characters int tm_mon Month, 0 to 11.


from string b over string a up to and int tm_year Years since 1900.
including \0, starting at the position of \0 in
int tm_wday Day of the week, 0 to 6.
string a. (safe)
int tm_yday Day of the year, 0 to 365.
strncmp(a, b, n) Compares first n characters of two strings.
int tm_isdst Daylight saving time.
Returns false if string a equals string b, true
otherwise. Ignores characters after \0. Functions
(safe) time(NULL) Returns unix epoch time
(seconds since 1/Jan/1970.)
Safe functions are those that let you specify the length of the input.
Unsafe functions do not, and carry the risk of memory overflow. time(&time_t); Stores the current time in a time
_t variable.
The Time Library ctime(&time_t) Returns a time_t variable as a
#include <time.h> string.

Variable Types x = localtime( &time_t); Breaks time_t down into stru

time_t Stores the calendar time. ct tm members.

struct tm *x; Stores a time & date breakdown.


Unary Operators
tm structure members:
by descending evaluation precedence
int tm_sec Seconds, 0 to 59.
+a Sum of 0 (zero) and a. (0 + a)
int tm_min Minutes, 0 to 59.
-a Difference of 0 (zero) and a. (0 - a)
int tm_hour Hours, 0 to 23.
!a Complement (logical NOT) of a. (~a)
int tm_mday Day of the month, 1 to 31.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 20 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Unary Operators (cont) Binary Operators (cont)

~a Binary ones complement (bitwise NOT) of a. (~a) a << b; Left bitwise shift of a by b places. (a × 2b)

++a Increment of a by 1. (a = a + 1) a >> b; Right bitwise shift of a by b places. (a × 2-b)

--a Decrement of a by 1. (a = a - 1) a < b; Less than. True if a is less than b and false otherwise.

a++ Returns a then increments a by 1. (a = a + 1) a <= b; Less than or equal to. True if a is less than or equal to b

a-- Returns a then decrements a by 1. (a = a - 1) and false otherwise. (a ≤ b)

(type)a Typecasts a as type. a > b; Greater than. True if a is greater than than b and false
otherwise.
&a; Memory location of a.
a >= b; Greater than or equal to. True if a is greater than or
sizeof(a) Memory size of a (or type) in bytes.
equal to b and false otherwise. (a ≥ b)

Binary Operators a == b; Equality. True if a is equal to b and false otherwise. (a


⇔ b)
by descending evaluation precedence
a != b; Inequality. True if a is not equal to b and false
a * b; Product of a and b. (a × b)
otherwise. (a ≠ b)
a / b; Quotient of dividend a and divisor b. Ensure divisor is
a & b; Bitwise AND of a and b. (a ⋂ b)
non-zero. (a ÷ b)
a ^ b; Bitwise exclusive-OR of a and b. (a ⊕ b)
a % b; Remainder of integers dividend a and divisor b.

a + b; Sum of a and b.

a - b; Difference of a and b.

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 21 of 22. https://readable.com
black/
ashlynblack.com
C Reference Cheat Sheet
by Ashlyn Black (Ashlyn Black) via cheatography.com/20410/cs/3196/

Binary Operators (cont) Ternary & Assignment Operators (cont)

a | b; Bitwise inclusive-OR of a and b. (a ⋃ b) a -= b; Assigns difference of a and b to a. (a = a - b)

a && b; Logical AND. True if both a and b are non-zero. (Logical a <<= b; Assigns left bitwise shift of a by b places to a. (a = a ×
AND) (a ⋂ b) 2b)
a || b; Logical OR. True if either a or b are non-zero. (Logical a >>= b; Assigns right bitwise shift of a by b places to a. (a = a
OR) (a ⋃ b) × 2 -b)
a &= b; Assigns bitwise AND of a and b to a. (a = a ⋂ b)
Ternary & Assignment Operators
a ^= b; Assigns bitwise exclus​ive-OR of a and b to a. (a = a ⊕
by descending evaluation precedence b)
x ? a : b; Evaluates a if x evaluates as true or b otherwise. a |= b; Assigns bitwise inclus​ive-OR of a and b to a. (a = a ⋃
(if(x){ a; } else { b; }) b)
x = a; Assigns value of a to x.

a *= b; Assigns product of a and b to a. (a = a × b) C Cheatsheet by Ashlyn Black

a /= b; Assigns quotient of dividend a and divisor b to a. (a ashlyn​bla​ck.com

= a ÷ b)
a %= b; Assigns remainder of integers dividend a and
divisor b to a. (a = a mod b)

a += b; Assigns sum of a and b to a. (a = a + b)

By Ashlyn Black (Ashlyn Published 28th January, 2015. Sponsored by Readable.com


Black) Last updated 12th May, 2016. Measure your website readability!
cheatography.com/ashlyn- Page 22 of 22. https://readable.com
black/
ashlynblack.com

You might also like