You are on page 1of 9

Number Literals Primitive Variable Types

Integers *applicable but not limited to most ARM, AVR, x86 & x64 installations

0b11111111 binary 0B11111111 binary [class] [qualifier] [unsigned] type/void name;

0377 octal 255 decimal by ascending arithmetic conversion

0xff hexadecimal 0xFF hexadecimal Integers

Type Bytes Value Range


Real Numbers
char 1 unsigned OR signed
88.0f / 88.1234567f
unsigned char 1 0 to 28-1
single precision float ( f suffix )
signed char 1 -27 to 27-1
88.0 / 88.123456789012345
int 2/4 unsigned OR signed
double precision float ( no f suffix )
unsigned int 2/4 0 to 216 -1 OR 231 -1
Signage
signed int 2/4 -215 to 215 -1 OR -231 to 232 -1
42 / +42 positive -42 negative
short 2 unsigned OR signed
Binary notation 0b... / 0B... is available on GCC and most but not all C
compilers. unsigned short 2 0 to 216 -1

signed short 2 -215 to 215 -1


Variables
long 4/8 unsigned OR signed
Declaring
unsigned long 4/8 0 to 232 -1 OR 264 -1
int x; A variable.
signed long 4/8 -231 to 231 -1 OR -263 to 263 -1
char x = 'C'; A variable & initialising it.
long long 8 unsigned OR signed
float x, y, z; Multiple variables of the same type.
unsigned long long 8 0 to 264 -1
const int x = 88; A constant variable: can't assign to after
signed long long 8 -263 to 263 -1
declaration (compiler enforced.)

Naming Floats

johnny5IsAlive;  Alphanumeric, not a keyword, begins with a Type Bytes Value Range (Norma lized)
letter.

2001ASpaceOddysey;  Doesn't begin with a letter. Primitive Variable Types (cont)


while;  Reserved keyword.
float 4 ±1.2×10-38 to ±3.4×1038
how exciting! ;  Non-alphanumeric.
double 8/ ±2.3×10-308 to ±1.7×10308 OR alias to float
iamaverylongvariablenameohmygoshyesiam;  4 for AVR.

Longer than 31 characters (C89 & C90 only) long double ARM: 8, AVR: 4, x86: 10, x64: 16

Constants are CAPITALISED. Function names usually take the form of a Qualifiers

verb eg. plotRobotUprising(). const type Flags variable as read-only (compiler can optimise.)

volatile type Flags variable as unpredictable (compiler cannot


optimise.)
Primitive Variable Types (cont)
Storage Classes
char x = 1, y = 2; float z = (float) x / y;
register Quick access required. May be stored in RAM OR a
Some types (denoted with OR) are architecture dependant. register. Maximum size is register size.

static Retained when out of scope. static global variables


There is no primitive boolean type, only zero (false, 0) and non-zero (true, are confined to the scope of the compiled object file
usually 1.) they were declared in.

extern Variable is declared by another file.

Typecasting

(type)a Returns a as data type.

C Reference Cheat Sheet


by Ashlyn Black via cheatography.com/20410/cs/3196/
Extended Variable Types Structures (cont)

[class] [qualifier] type name; struct strctName A strctName structure type pointer,
*ptrName; ptrName.
by ascending arithmetic conver sion

From the stdint.h Library struct strctName{ type Shorthand for defining strctName and
a; type b; } varName; declaring varName as that structure
Type Bytes Value Range
type.
int8_t 1 -27 to 27-1
struct strctName A variable varName as structure type
uint8_t 1 0 to 28-1 varName = { a, b }; strctName and initialising its members.
int16_t 2 -215 to 215 -1 Accessing
uint16_t 2 0 to 216 -1 varName.x Member x of structure varName.

int32_t 4 -231 to 231 -1 ptrName->x Value of structure pointer ptrName

uint32_t 4 0 to 232 -1 member x.

int64_t 8 -263 to 263 -1 Bit Fields

uint64_t 8 0 to 264 -1 struct{char a:4, b:4} Declares x with two membersa and b,
x; both four bits in size (0 to 15.)
From the stdbool.h Library
Array members can't be assigned bit fields.
Type Bytes Value Range

bool 1 true / false or 0 / 1


Type Definitions

The stdint.h library was introduced in C99 to give integer types Defining
architecture-independent lengths.
typedef unsigned short uint16; Abbreviating a longer type
Structures name to uint16.

Defining typedef struct structName{int Creating a newType from a


a, b;}newType; structure.
struct strctName{ A structure type strctName with two
type x; type y; }; members, x and y. Note trailing semicolon typedef enum typeName{false, Creating an enumerated bool
true}bool; type.
struct item{ struct A structure with a recursive structure pointer
item *next; }; inside. Useful for linked lists. Declaring

Declaring uint16 x = 65535; Variable x as type uint16.

struct strctName A variable varName as structure type newType y = {0, 0}; Structure y as type newType.

varName; strctName.

Pointers

Declaring

type *x; Pointers have a datatype like normal variables.


Pointers (cont)
Unions
void *v; They can also have an incomplete type. Operators other
than assignment cannot be applied as the length of the type Defining

is unknown. union uName{int A union type uName with two members,x & y.
struct A data structure pointer. x; char y[8];} Size is same as biggest member size.
type *y;
Declaring
type An array/string name can be used as a pointer to the first union uN vName; A variable vName as union type uN.
z[]; array element.
Accessing
Accessing
vName.y[int] Members cannot store values concurrently.
x A memory address. Setting y will corrupt x.

*x Value stored at that address. Unions are used for storing multiple data types in the same area

y->a Value stored in structure pointery member a. of memory.

&varName Memory address of normal variable varName.

*(type Dereferencing a void pointer as atype pointer.


*)v

A pointer is a variable that holds a memory location.


Enumeration Arrays

Defining Declaring

enum bool { A custom data type bool with two possible type name[int]; You set array length.
false, true }; states: false or true.
type name[int] = {x, You set array length and initialise
Declaring y, z}; elements.

enum bool A variable varName of data type bool. type name[int] = {x}; You set array length and initialise all
varName; elements to x.

Assigning type name[] = {x, y, Compiler sets array length based on initial
z}; elements.
varName = true; Variable varName can only be assigned values
of either false or true. Size cannot be changed after declaration.

Evaluating Dimensions
if(varName == Testing the value of varName. name[int] One dimension array.
false)
name[int][int] Two dimensional array.

Escape Characters Accessing

name[int] Value of element int in array name.


\a alarm (bell/beep) \b backspace

\f formfeed \n newline Arrays (cont)


\r carriage return \t horizontal tab
*(name + int) Same as name[int].
\v vertical tab \\ backslash
Elements are contiguously numbered ascending from0.
\' single quote \" double quote
&name[int] Memory address of element int in
\? question mark array name.

\nnn Any octal ANSI character code. name + int Same as &name[int].

\xhh Any hexadecimal ANSI character code. Elements are stored in contiguous memory.

Console Input/Output (cont) Measuring

sizeof(array) / Returns length of array. (Unsafe)


gets(strName) Reads a line from the input stream into a string
variable. (Unsafe, removed in C11.) sizeof(arrayType)

Alternative sizeof(array) / Returns length of array. (Safe)

fgets(strName, Reads a line from the input stream into a string sizeof(array[0])

length, stdin); variable. (Safe)


Strings
puts("string") Prints a string to the output stream.
'A' character Single quotes.
Formatted Data
"AB" string Double quotes.
scanf("%d", &x) Read value/s (type defined by format string) into
variable/s (type must match) from the input stream. \0 Null terminator.
Stops reading at the first whitespace. & prefix not Strings are char arrays.
required for arrays (including strings.) (unsafe)
char name[4] = "Ash";
printf("I love Prints data (formats defined by the format string) as
a string to the output stream. is equivalent to
%c %d!", 'C',
99) char name[4] = {'A', 's', 'h', '\0'};

Alternative int i; for(i = 0; name[i]; i++){}

fgets(strName, Uses fgets to limit the input length, then uses \0 evaluates as false.

length, stdin); sscanf to read the resulting string in place of


Strings must include achar element for \0.
sscanf(strName, scanf. (safe)
"%d", &x);

The stream buffers must be flushed to reflect changes. String 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.
Functions Functions (cont)

Declaring type f(){ static Returning an array/string/structure by pointer.


type x[]; return The static qualifier is necessary otherwise
type/void funcName([args...]){ [return var;] }
&x; } x won't exist after the function exits.
Function names follow the same restrictions as variable names but must
also be unique. Passing by pointer allows you to change the originating variable within the
function.
type/void Return value type (void if none.)
Scope
funcName() Function name and argument parenthesis.
int f(){ int i = 0; } i++; 
args... Argument types & names (void if none.)
i is declared inside f(), it doesn't exist outside that function.
{} Function content delimiters.
Prototyping
return var; Value to return to function call origin. Skip for void
type funcName(args...);
type functions. Functions exit immediately after a
return. Place before declaring or referencing respective function (usually before
main.)
By Value vs By Pointer
type Same type, name and args... as
void f(type Passing variable y to function f argument x (by
funcName([args...]) respective function.
x); f(y); value.)
; Semicolon instead of function delimiters.
void f(type Passing an array/string to function f argument x (by
*x); pointer.)
main()
f(array);
int main(int argc, char *argv[]){return int;}
void f(type Passing a structure to function f argument x (by
*x); pointer.) Anatomy
f(structure); int main Program entry point.

void f(type Passing variable y to function f argument x (by int argc # of command line arguments.
*x); f( &y); pointer.)
char *argv[] Command line arguments in an array of strings. #1 is
type f(){ Returning by value. always the program filename.
return x; } return int; Exit status (integer) returned to the OS upon

type f(){ type Returning a variable by pointer. program exit.

x; return &x; Command Line Arguments


} app two 3 Three arguments, "app", "two" and "3".

Iterative (Looping) app "two 3" Two arguments, "app" and "two 3".

while main is the first function called when the program executes.

int x = 0; while(x < 10){ x += 2; }

Loop skipped if test condition initially false.

int x = 0; Declare and initialise integer x.

while() Loop keyword and condition parenthesis.

x < 10 Test condition.

{} Loop delimiters.

x += 2; Loop contents.

do while

char c = 'A'; do { c++; } while(c != 'Z');

Always runs through loop at least once.

char c = 'A'; Declare and initialise character c.


Conditional (Branching) Iterative (Looping) (cont)

if, else if, else do Loop keyword.

if(a) b; Evaluates b if a is true. {} Loop delimiters.

if(a){ b; c; } Evaluates b and c if a is true. c++; Loop contents.

if(a){ b; }else{ c; } Evaluates b if a is true, c while(); Loop keyword and condition parenthesis. Note
otherwise. semicolon.

if(a){ b; }else if(c){ d; Evaluates b if a is true, c != 'Z' Test condition.

}else{ e; } otherwise d if c is true, for


otherwise e.
int i; for(i = 0; n[i] != '\0'; i++){} (C89)
switch, case, break
OR
switch(a){ case b: c; } Evaluates c if a equals b.
for(int i = 0; n[i] != '\0'; i++){} (C99+)
switch(a){ default: b; } Evaluates b if a matches no
Compact increment/decrement based loop.
other case.
int i; Declares integer i.
switch(a){ case b: case c: Evaluates d if a equals either b
for() Loop keyword.
d; } or c.
i = 0; Initialises integer i. Semicolon.
switch(a){ case b: c; case Evaluates c, e and f if a equals
d: e; default: f; } b, e and f if a equals d, n[i] != Test condition. Semicolon.

otherwise f. '\0';

switch(a){ case b: c; break; Evaluates c if a equals b, e if a i++ Increments i. No semicolon.

case d: e; break; default: f; equals d and e otherwise. {} Loop delimiters.


}
continue

Console Input/Output int i=0; while(i<10){ i++; continue; i--;}

#include <stdio.h> Skips rest of loop contents and restarts at the beginning of the loop.

break
Characters
int i=0; while(1){ if(x==10){break;} i++; }
getchar() Returns a single character's ANSI code from the input
stream buffer as an integer. (safe) Skips rest of loop contents and exits loop.
putchar(int) Prints a single character from an ANSI code integer to
the output stream buffer.

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

#include <stdio.h> fseek(fptr, Sets current file position. Returns false is


offset, origin); successful, true otherwise. The offset is a
Opening
long integer type.
FILE *fptr = fopen(filename, mode);
Origins
FILE *fptr Declares fptr as a FILE type pointer (stores stream
SEEK_SET Beginning of file.
location instead of memory location.)
SEEK_CUR Current position in file.
fopen() Returns a stream location pointer if successful,0
SEEK_END End of file.
otherwise.

filename String containing file's directory path & name. Utilities

mode String specifying the file access mode. feof(fptr) Tests end-of-file indicator.

Modes rename(strOldName, Renames a file.


strNewName)
"r" / "rb" Read existing text/binary file.
remove(strName) Deletes a file.
"w" / "wb" Write new/over existing text/binary file.
Characters
"a" / "ab" Write new/append to existing text/binary file.
fgetc(fptr) Returns character read or EOF if
"r+" / "r+b" / Read and write existing text/binary file.
unsucc​essful. (safe)
"rb+"
fputc(int c, fptr) Returns character written or EOF if
"w+" / "w+b" / Read and write new/over existing text/binary file. unsucc​essful.
"wb+"
Strings
"a+" / "a+b" / Read and write new/append to existing text/binary fgets(char *s, int Reads n-1 characters from file fptr into string
"ab+" file.
n, fptr) s. Stops at EOF and \n. (safe)
Closing fputs(char *s, Writes string s to file fptr. Returns non-
fclose(fptr); Flushes buffers and closes stream. Returns 0 if fptr) ne​gative on success, EOF otherwise.
successful, EOF otherwise.
Formatted Data
Random Access fscanf(fptr, Same as scanf with additional file pointer
ftell(fptr) Return current file position as a long integer. format, [...]) parameter. (unsafe)

fprintf(fptr, Same as printf with additional file pointer


File Input/​Output (cont)
format, [...]) parameter.
fgets(strName, Uses fgets to limit the input length, then
Alternative
length, fptr); uses sscanf to read the resulting string
sscanf(strName, "%d", in place of scanf. (safe)
&x);

Binary

fread(void *ptr, Reads a number of elements from


sizeof(element), fptr to array *ptr. (safe)
number, fptr)

fwrite(void *ptr, Writes a number of elements to file


sizeof(element), fptr from array *ptr.
number, fptr)

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

C Reference Cheat Sheet


by Ashlyn Black via cheatography.com/20410/cs/3196/
Placeholder Types (f/printf And f/scanf)
Placeholder Formatting (f/printf And f/scanf) (cont)
printf("%d%d...", arg1, arg2...);
.* Precision specified by a preceding argument in printf.
Type Example Description
Length
%d or %i -42 Signed decimal integer.
hh Display a char as int.
%u 42 Unsigned decimal integer.
h Display a short as int.
%o 52 Unsigned octal integer.
l Display a long integer.
%x or %X 2a or 2A Unsigned hexadecimal
ll Display a long long integer.
integer.

%f or %F 1.21 Signed decimal float. L Display a long double float.

%e or %E 1.21e+9 or 1.21E+9 Signed decimal w/ scientific z Display a size_t integer.

notation. j Display a intmax_t integer.


%g or %G 1.21e+9 or 1.21E+9 Shortest representation of
t Display a ptrdiff_t integer.
%f/%F or %e/%E.

%a or %A 0x1.207c8ap+30 or Signed hexadecimal float. Preprocessor Directives


0X1.207C8AP+30
#include Replaces line with contents of a standard C header
%c a A character. <inbuilt.h> file.

%s A String. A character string. #include Replaces line with contents of a custom header file.
"./custom.h" Note dir path prefix & quotations.

Placeholder Types (f/printf And f/scanf) (cont) #define NAME Replaces all occurrences of NAME with value.
value
%p A pointer.

%% % A percent character. Comments


%n No output, saves # of characters printed so far. Respective printf
// We're single-line comments!
argument must be an integer pointer.
// Nothing compiled after // on these lines.
The pointer format is architecture and implementation dependant. /* I'm a multi-line comment!
Nothing compiled between
Placeholder Formatting (f/printf And f/scanf)
these delimiters. */
%[Flags][Width][.Precision][Length]Type
C Reserved Keywords
Flags

- Left justify instead of default right justify. _Alignas break float signed

+ Sign for both positive numbers and negative. _Alignof case for sizeof

# Precede with 0, 0x or 0X for %o, %x and %X tokens. _Atomic char goto static

space Left pad with spaces. _Bool const if struct

0 Left pad with zeroes. _Complex continue inline switch

Width _Generic default int typedef

integer Minimum number of characters to print: invokes padding if _Imaginary do long union
necessary. Will not truncate.
C Reserved Keywords (cont)
* Width specified by a preceding argument in printf.
_Noreturn double register unsigned
Precision
_Static_assert else restrict void
.integer Minimum # of digits to print for %d, %i, %o, %u, %x, %X. Left
pads with zeroes. Will not truncate. Skips values of 0. _Thread_local enum return volatile

Minimum # of digits to print after decimal point for %a, %A, auto extern short while
%e, %E, %f, %F (default of 6.) _A-Z... __...
Minimum # of significant digits to print for %g & %G.
C / POSIX Reserved Keywords
Maximum # of characters to print from %s (a string.)
E[0-9]... E[A-Z]... is[a-z]... to[a-z]...
. If no integer is given, default of 0.
LC_[A-Z]... SIG[A-Z]... SIG_[A-Z]... str[a-z]...

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


The Character Type Library Heap Space

#include <ctype.h> #include <stdlib.h>

tolower(char) Lowercase char. Allocating

toupper(char) Uppercase char. malloc(); Returns a memory location if


successful, NULL otherwise.
isalpha(char) True if char is a letter of the alphabet, false
otherwise. type *x; x = Memory for a variable.
malloc(sizeof(type));
islower(char) True if char is a lowercase letter of the alphabet,
false otherwise. type *y; y = Memory for an array/string.

isupper(char) True if char is an uppercase letter of the alphabet, malloc(sizeof(type) *

false otherwise. length );

isnumber(char) True if char is numerical (0 to 9) and false struct type *z; z = Memory for a structure.
otherwise. malloc(sizeof(struct
type));
The Character Type Library (cont)
Deallocating
isblank True if char is a whitespace character (' ', '\t', '\n' )
free(ptrName); Removes the memory allocated
and false otherwise.
to ptrName.
The Standard Library
Reallocating
#include <stdlib.h> realloc(ptrName, size); Attempts to resize the memory

Randomicity block assigned to ptrName.

rand() Returns a (predictable) random integer between 0 The memory addresses you see are from virtual memory the operating
and RAND_MAX based on the randomiser seed. system assigns to the program; they are not physical addresses.

RAND_MAX The maximum value rand() can generate.


Referencing memory that isn't assigned to the program will produce an
srand(unsigned Seeds the randomiser with a positive integer. OS segmentation fault.
integer);
Unary Operators
(unsigned) Returns the computer's tick-tock value. Updates
time(NULL) every second. by descending evaluation preced ence

+a Sum of 0 (zero) and a. (0 + a)


The Standard Library (cont)
-a Difference of 0 (zero) and a. (0 - a)
Sorting
!a Complement (logical NOT) of a. (~a)
qsort(array, length, sizeof(type), compFunc);
~a Binary ones complement (bitwise NOT) of a. (~a)
qsort() Sort using the QuickSort algorithm.
++a Increment of a by 1. (a = a + 1)
array Array/string name.
--a Decrement of a by 1. (a = a - 1)
length Length of the array/string.
Unary
a++ Operators
Returns a(cont)
then increments a by 1. (a = a + 1)
sizeof(type) Byte size of each element.
a-- Returns a then decrements a by 1. (a = a - 1)
compFunc Comparison function name.
(type)a Typecasts a as type.
compFunc
&a; Memory location of a.
int compFunc( const void *a, const void b* ){ return(
*(int *)a - *(int *)b); } sizeof(a) Memory size of a (or type) in bytes.

int compFunc() Function name unimportant but must return an


integer.

const void *a, Argument names unimportant but must identical


const void *b otherwise.

return( *(int *)a Negative result swaps b for a, positive result


- *(int *)b); swaps a for b, a result of 0 doesn't swap.

C's inbuilt randomiser is cryptographically insecure: DO NOT use it for


security applications.
The String Library
The Time Library

#include <time.h> #include <string.h>

Variable Types strlen(a) Returns # of char in string a as an integer.

time_t Stores the calendar time. Excludes \0. (unsafe)

struct tm *x; Stores a time & date breakdown. strcpy(a, b) Copies strings. Copies string b over string a up
to and including \0. (unsafe)
tm structure members:
strcat(a, b) Concatenates strings. Copies string b over
int tm_sec Seconds, 0 to 59.
string a up to and including \0, starting at the
int tm_min Minutes, 0 to 59.
position of \0 in string a. (unsafe)
int tm_hour Hours, 0 to 23.
strcmp(a, b) Compares strings. Returns false if string a
int tm_mday Day of the month, 1 to 31. equals string b, true otherwise. Ignores

int tm_mon Month, 0 to 11. characters after \0. (unsafe)

int tm_year Years since 1900. strstr(a, b) Searches for string b inside string a. Returns a
pointer if successful, NULL otherwise. (unsafe)
int tm_wday Day of the week, 0 to 6.
Alternatives
int tm_yday Day of the year, 0 to 365.
strncpy(a, b, n) Copies strings. Copies n characters from string b
int tm_isdst Daylight saving time.
over string a up to and including \0. (safe)
Functions
strncat(a, b, n) Concatenates strings. Copies n characters from
time(NULL) Returns unix epoch time (seconds since
string b over string a up to and including \0,
1/Jan/1970.)
starting at the position of \0 in string a. (safe)
time(&time_t); Stores the current time in a time_t
strncmp(a, b, n) Compares first n characters of two strings.
variable.
Returns false if string a equals string b, true
ctime(&time_t) Returns a time_t variable as a string.
otherwise. Ignores characters after \0.
x = localtime( Breaks time_t down into struct tm
Binary Operators (cont)(safe)
&time_t); members.
a | b; Bitwise inclusive-OR of a and b. (a ⋃
b)
Binary Operators a && b; Logical AND. True if both a and b are non-zero.

by descending evaluation preced ence (Logical AND) (a ⋂ b)


a || b; Logical OR. True if either a or b are non-zero. (Logical OR)
a * b; Product of a and b. (a × b)
(a
a / b; Quotient of dividend a and divisor b. Ensure divisor is non- ⋃ b)
Ternary & Assignment Operators
zero. (a ÷ b)

a % b; Remainder of integers dividend a and divisor b. by descending evaluation precedence

x ? a : b; Evaluates a if x evaluates as true or b otherwise. (if(x){ a;


a + b; Sum of a and b.
} else { b; })
a - b; Difference of a and b.
x = a; Assigns value of a to x.
a << b; Left bitwise shift of a by b places. (a × 2b )
a *= b; Assigns product of a and b to a. (a = a × b)
a >> b; Right bitwise shift of a by b places. (a × 2-b )
a /= b; Assigns quotient of dividend a and divisor b to a. (a = a ÷
a < b; Less than. True if a is less than b and false otherwise.
b)
a <= b; Less than or equal to. True if a is less than or equal to b and a %= b; Assigns remainder of integers dividend a and divisor b to
false otherwise. (a ≤ b) a. (a = a mod b)
a > b; Greater than. True if a is greater than than b and false
a += b; Assigns sum of a and b to a. (a = a + b)
otherwise.
a -= b; Assigns difference of a and b to a. (a = a - b)
a >= b; Greater than or equal to. True if a is greater than or equal to
a <<= b; Assigns left bitwise shift of a by b places to a. (a = a ×
b and false otherwise. (a ≥ b)
2b)
a == b; Equality. True if a is equal to b and false otherwise. (a ⇔ b)
a >>= b; Assigns right bitwise shift of a by b places to a. (a = a ×
a != b; Inequality. True if a is not equal to b and false otherwise. (a ≠
2-b)
b)
a &= b; Assigns bitwise AND of a and b to a. (a = a ⋂ b)
a & b; Bitwise AND of a and b. (a ⋂ b)
a ^= b; Assigns bitwise exclusive-OR of a and b to a. (a = a ⊕ b)
a ^ b; Bitwise exclusive-OR of a and b. (a ⊕ b)
a |= b; Assigns bitwise inclusive-OR of a and b to a. (a = a ⋃ b)

You might also like