C Cheat Sheet
C Cheat Sheet
42 / +42 positive -42 negative signed long 4/8 -231 to 231 -1 OR -263 to 263 -1
Binary notation 0b... / 0B... is available on GCC and most but not all C long long 8 unsigned OR signed
compilers. unsigned long 8 0 to 264 -1
long
Variables signed long long 8 -263 to 263 -1
Declaring Floats
int x; A variable. Type Bytes Value Range (Normalized)
char x = 'C'; A variable & initialising it. float 4 ±1.2×10-38 to ±3.4×1038
float x, y, z; Multiple variables of the same type. double 8/4 ±2.3×10-308 to ±1.7×10308 OR alias to float
const int x = 88; A constant variable: can't assign to after for AVR.
declaration (compiler enforced.) long double ARM: 8, AVR: 4, x86: 10, x64: 16
Naming Qualifiers
johnny5IsAlive; Alphanumeric, not a keyword, begins with a const type Flags variable as read-only (compiler can optimise.)
letter.
volatile type Flags variable as unpredictable (compiler cannot
2001ASpaceOddysey; Doesn't begin with a letter. optimise.)
while; Reserved keyword.
iamaverylongvariablenameohmygoshyesiam;
*applicable but not limited to most ARM, AVR, x86 & x64 installations
Integers
register Quick access required. May be stored in RAMOR a register. struct strctName{ type x; A structure type strctName with two members,
Maximum size is register size. type y; }; x and y. Note trailing semicolon
static Retained when out of scope. static global variables are confined struct item{ struct item A structure with a recursive structure pointer
to the scope of the compiled object file they were declared in. *next; }; inside. Useful for linked lists.
Type Bytes Value Range struct{char a:4, b:4} x; Declares x with two members a and b, both
four bits in size (0 to 15.)
int8_t 1 -27 to 27-1
Array members can't be assigned bit fields.
uint8_t 1 0 to 28-1
From the stdbool.h Library typedef enum typeName{false, Creating an enumerated bool type.
true}bool;
Type Bytes Value Range
Declaring
bool 1 true / false or 0 / 1
uint16 x = 65535; Variable x as type uint16.
The stdint.h library was introduced in C99 to give integer types
architecture-independent lengths. newType y = {0, 0}; Structure y as type newType.
union uName{int A union type uName with two members, x & y. Size is y->a Value stored in structure pointery member a.
x; char y[8];} same as biggest member size. &varName Memory address of normal variable varName.
Declaring *(type *)v Dereferencing a void pointer as atype pointer.
union uN vName; A variable vName as union type uN.
A pointer is a variable that holds a memory location.
Accessing
Enumeration type name[int] = {x}; You set array length and initialise all
elements to x.
Defining
type name[] = {x, y, z}; Compiler sets array length based on initial
enum bool { false, A custom data type bool with two possible states:
elements.
true }; false or true.
Size cannot be changed after declaration.
Declaring
Dimensions
enum bool A variable varName of data type bool.
name[int] One dimension array.
varName;
name[int][int] Two dimensional array.
Assigning
Accessing
varName = true; Variable varName can only be assigned values of
either false or true. name[int] Value of element int in array name.
if(varName == Testing the value of varName. Elements are contiguously numbered ascending from 0.
false) &name[int] Memory address of element int in array
name.
Pointers name + int Same as &name[int].
Declaring Elements are stored in contiguous memory.
type Pointers have a data type like normal variables. Measuring
*x;
sizeof(array) / Returns length of array. (Unsafe)
void They can also have an incomplete type. Operators other than sizeof(arrayType)
*v; assignment cannot be applied as the length of the type is
sizeof(array) / Returns length of array. (Safe)
unknown.
sizeof(array[0])
struct A data structure pointer.
type
Strings
*y;
'A' character Single quotes.
type An array/string name can be used as a pointer to the first array
z[]; element. "AB" string Double quotes.
char name[4] = "Ash"; void f(type *x); Passing a structure to function f argument x (by
char name[4] = {'A', 's', 'h', '\0'}; void f(type *x); Passing variable y to function f argument x (by
f(&y); pointer.)
int i; for(i = 0; name[i]; i++){}
type f(){ return x; } Returning by value.
\0 evaluates as false.
type f(){ type x; Returning a variable by pointer.
Strings must include a char element for \0. return &x; }
\f formfeed \n newline Passing by pointer allows you to change the originating variable within the
function.
\r carriage return \t horizontal tab
Scope
\v vertical tab \\ backslash
int f(){ int i = 0; } i++;
\' single quote \" double quote
i is declared inside f(), it doesn't exist outside that function.
\? question mark
Prototyping
\nnn Any octal ANSI character code.
type funcName(args...);
\xhh Any hexadecimal ANSI character code.
Place before declaring or referencing respective function (usually before
main.)
Functions
type Same type, name and args... as respective function.
Declaring
funcName([args...])
type/void funcName([args...]){ [return var;] }
; Semicolon instead of function delimiters.
Function names follow the same restrictions as variable names but must
also be unique.
main()
type/void Return value type (void if none.)
int main(int argc, char *argv[]){return int;}
funcName() Function name and argument parenthesis.
Anatomy
args... Argument types & names (void if none.)
int main Program entry point.
{} Function content delimiters.
int argc # of command line arguments.
return var; Value to return to function call origin. Skip for void type
char *argv[] Command line arguments in an array of strings. #1 is
functions. Functions exit immediately after a return.
always the program filename.
By Value vs By Pointer
return int; Exit status (integer) returned to the OS upon program exit.
void f(type Passing variable y to function f argument x (by value.)
Command Line Arguments
x); f(y);
app two 3 Three arguments, "app", "two" and "3".
void f(type Passing an array/string to function f argument x (by pointer.)
*x); app "two 3" Two arguments, "app" and "two 3".
f(array); main is the first function called when the program executes.
if, else if, else int i; for(i = 0; n[i] != '\0'; i++){} (C89)
if(a){ b; }else if(c){ d; }else{ e; } Evaluates b if a is true, otherwise d if c int i; Declares integer i.
is true, otherwise e. for() Loop keyword.
switch, case, break i = 0; Initialises integer i. Semicolon.
switch(a){ case b: c; } Evaluates c if a equals b. n[i] != '\0'; Test condition. Semicolon.
switch(a){ default: b; } Evaluates b if a matches no other i++ Increments i. No semicolon.
case.
{} Loop delimiters.
switch(a){ case b: case c: d; } Evaluates d if a equals either b or c.
continue
switch(a){ case b: c; case d: e; Evaluates c, e and f if a equals b, e
int i=0; while(i<10){ i++; continue; i--;}
default: f; } and f if a equals d, otherwise f.
Skips rest of loop contents and restarts at the beginning of the loop.
switch(a){ case b: c; break; case Evaluates c if a equals b, e if a equals
d: e; break; default: f; } d and e otherwise. break
while() Loop keyword and condition parenthesis. getchar() Returns a single character's ANSI code from the input
stream buffer as an integer. (safe)
x < 10 Test condition.
putchar(int) Prints a single character from an ANSI codeinteger to
{} Loop delimiters.
the output stream buffer.
x += 2; Loop contents.
Strings
do while
gets(strName) Reads a line from the input stream into a string
char c = 'A'; do { c++; } while(c != 'Z'); variable. (Unsafe, removed in C11.)
Always runs through loop at least once.
Alternative
char c = 'A'; Declare and initialise characterc. fgets(strName, Reads a line from the input stream into a string
do Loop keyword. length, stdin); variable. (Safe)
for
scanf("%d", &x) Read value/s (type defined by format string) into "a" / "ab" Write new/append to existing text/binary file.
variable/s (type must match) from the input stream. "r+" / "r+b" / "rb+" Read and write existing text/binary file.
Stops reading at the first whitespace. & prefix not
"w+" / "w+b" / "wb+" Read and write new/over existing text/binary file.
required for arrays (including strings.) (unsafe)
"a+" / "a+b" / "ab+" Read and write new/append to existing text/binary
printf("I love %c Prints data (formats defined by the format string) as a
file.
%d!", 'C', 99) string to the output stream.
Closing
Alternative
fclose(fptr); Flushes buffers and closes stream. Returns 0 if
fgets(strName, Uses fgets to limit the input length, then uses sscanf to
successful, EOF otherwise.
length, stdin); read the resulting string in place of scanf. (safe)
sscanf(strName, Random Access
"%d", &x); ftell(fptr) Return current file position as a long integer.
The stream buffers must be flushed to reflect changes. String terminator fseek(fptr, offset, Sets current file position. Returns false is
characters can flush the output while newline characters can flush the origin); successful, true otherwise. The offset is a long
input. integer type.
Origins
Safe functions are those that let you specify the length of the input. Unsafe
functions do not, and carry the risk of memory overflow. SEEK_SET Beginning of file.
filename String containing file's directory path & name. fgetc(fptr) Returns character read or EOF if unsuccessful.
(safe)
mode String specifying the file access mode.
fputc(int c, fptr) Returns character written or EOF if unsuccessful.
Modes
Strings
"r" / "rb" Read existing text/binary file.
fgets(char *s, int n, Reads n-1 characters from file fptr into string s.
"w" / Write new/over existing text/binary file.
fptr) Stops at EOF and \n. (safe)
"wb"
fputs(char *s, fptr) Writes string s to file fptr. Returns non-negative on
success, EOF otherwise.
Formatted Data
fscanf(fptr, format, [...]) Same as scanf with additional file pointer %% % A percent character.
parameter. (unsafe) %n No output, saves # of characters printed so far. Respective printf
fprintf(fptr, format, [...]) Same as printf with additional file pointer argument must be an integer pointer.
parameter.
The pointer format is architecture and implementation dependant.
Alternative
fgets(strName, length, Uses fgets to limit the input length, then uses Placeholder Formatting (f/printf And f/scanf)
fptr); sscanf(strName, sscanf to read the resulting string in place of
%[Flags][Width][.Precision][Length]Type
"%d", &x); scanf. (safe)
Flags
Binary
- Left justify instead of default right justify.
fread(void *ptr, Reads a number of elements from fptr to array
sizeof(element), *ptr. (safe) + Sign for both positive numbers and negative.
number, fptr) # Precede with 0, 0x or 0X for %o, %x and %X tokens.
fwrite(void *ptr, Writes a number of elements to file fptr from space Left pad with spaces.
sizeof(element), array *ptr.
0 Left pad with zeroes.
number, fptr)
Width
Safe functions are those that let you specify the length of the input. Unsafe
integer Minimum number of characters to print: invokes padding if
functions do not, and carry the risk of memory overflow.
necessary. Will not truncate.
Placeholder Types (f/printf And f/scanf) * Width specified by a preceding argument inprintf.
Precision
printf("%d%d...", arg1, arg2...);
.integer Minimum # of digits to print for %d, %i, %o, %u, %x, %X. Left
Type Example Description
pads with zeroes. Will not truncate. Skips values of 0.
%d or %i -42 Signed decimal integer.
Minimum # of digits to print after decimal point for%a, %A, %e,
%u 42 Unsigned decimal integer. %E, %f, %F (default of 6.)
%o 52 Unsigned octal integer. Minimum # of significant digits to print for %g & %G.
%x or %X 2a or 2A Unsigned hexadecimal integer. Maximum # of characters to print from %s (a string.)
%f or %F 1.21 Signed decimal float. . If no integer is given, default of 0.
%e or %E 1.21e+9 or 1.21E+9 Signed decimal w/ scientific .* Precision specified by a preceding argument inprintf.
notation.
Length
%g or %G 1.21e+9 or 1.21E+9 Shortest representation of
hh Display a char as int.
%f/%F or %e/%E.
h Display a short as int.
%a or %A 0x1.207c8ap+30 or Signed hexadecimal float.
0X1.207C8AP+30 l Display a long integer.
l_... fcntl.h
Preprocessor Directives
F_... fcntl.h
#include Replaces line with contents of a standard C header file. O_... fcntl.h
<inbuilt.h>
S_... fcntl.h
#include Replaces line with contents of a custom header file.Note
gr_... grp.h
"./custom.h" dir path prefix & quotations.
..._MAX limits.h
#define Replaces all occurrences of NAME with value.
NAME value pw_... pwd.h
sa_... signal.h
Comments SA_... signal.h
// We're single-line comments! st_... sys/stat.h
// Nothing compiled after // on these lines.
S_... sys/stat.h
/* I'm a multi-line comment!
Nothing compiled between tms_... sys/times.h
V... termios.h
C Reserved Keywords
I... termios.h
_Alignas break float signed O... termios.h
_Alignof case for sizeof TC... termios.h
_Atomic char goto static B[0-9]... termios.h
_Bool const if struct GNU Reserved Names
_Complex continue inline switch
Reallocating
Referencing memory that isn't assigned to the program will produce an OS islower(char) True if char is a lowercase letter of the alphabet, false
segmentation fault. otherwise.
isblank True if char is a whitespace character (' ', '\t', '\n') and
Randomicity
false otherwise.
rand() Returns a (predictable) random integer between 0 and
RAND_MAX based on the randomiser seed.
The String Library
RAND_MAX The maximum value rand() can generate.
#include <string.h>
srand(unsigned Seeds the randomiser with a positive integer.
integer); strlen(a) Returns # of char in string a as an integer. Excludes \0.
(unsafe)
(unsigned) Returns the computer's tick-tock value. Updates every
time(NULL) second. strcpy(a, b) Copies strings. Copies string b over string a up to and
including \0. (unsafe)
Sorting
strcat(a, b) Concatenates strings. Copies string b over string a up to
qsort(array, length, sizeof(type), compFunc);
and including \0, starting at the position of \0 in string a.
qsort() Sort using the QuickSort algorithm. (unsafe)
array Array/string name. strcmp(a, b) Compares strings. Returns false if string a equals string
length Length of the array/string. b, true otherwise. Ignores characters after \0. (unsafe)
sizeof(type) Byte size of each element. strstr(a, b) Searches for string b inside string a. Returns a pointer if
successful, NULL otherwise. (unsafe)
compFunc Comparison function name.
Alternatives
compFunc
strncpy(a, b, n) Copies strings. Copies n characters from string b over
int compFunc( const void *a, const void b* ){ return( *(int *)a - *(int *)b); }
string a up to and including \0. (safe)
int compFunc() Function name unimportant but must return an integer.
strncat(a, b, n) Concatenates strings. Copies n characters from string b
const void *a, Argument names unimportant but must identical over string a up to and including \0, starting at the
const void *b otherwise. position of \0 in string a. (safe)
return( *(int *)a Negative result swaps b for a, positive result swaps a for
- *(int *)b); b, a result of 0 doesn't swap.
strncmp(a, b, n) Compares first n characters of two strings. Returns a++ Returns a then increments a by 1. (a = a + 1)
false if string a equals string b, true otherwise. Ignores a-- Returns a then decrements a by 1. (a = a - 1)
characters after \0. (safe)
(type)a Typecasts a as type.
Safe functions are those that let you specify the length of the input. Unsafe
&a; Memory location of a.
functions do not, and carry the risk of memory overflow.
sizeof(a) Memory size of a (or type) in bytes.
Functions a >= b; Greater than or equal to. True if a is greater than or equal to b
and false otherwise. (a ≥ b)
time(NULL) Returns unix epoch time (seconds since
1/Jan/1970.) a == b; Equality. True if a is equal to b and false otherwise. (a ⇔ b)
time(&time_t); Stores the current time in atime_t variable. a != b; Inequality. True if a is not equal to b and false otherwise. (a ≠ b)
x = localtime( Breaks time_t down into struct tm members. a ^ b; Bitwise exclusive-OR of a and b. (a ⊕ b)
&time_t); a | b; Bitwise inclusive-OR of a and b. (a ⋃ b)
a && b; Logical AND. True if both a and b are non-zero. (Logical AND)
Unary Operators (a ⋂ b)
by descending evaluation precedence a || b; Logical OR. True if either a or b are non-zero. (Logical OR) (a ⋃
++a Increment of a by 1. (a = a + 1)
--a Decrement of a by 1. (a = a - 1)
x = a; Assigns value of a to x.
ashlynblack.com