0% found this document useful (0 votes)
519 views

C Cheat Sheet

This document provides a summary of C variable types, number formats, and other C language fundamentals. It defines integer, float, character and other primitive variable types along with their byte sizes and value ranges. It also covers typecasting, qualifiers like const, structures, enumerated types and more. Key concepts are presented concisely for quick reference.

Uploaded by

Shining Chris
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)
519 views

C Cheat Sheet

This document provides a summary of C variable types, number formats, and other C language fundamentals. It defines integer, float, character and other primitive variable types along with their byte sizes and value ranges. It also covers typecasting, qualifiers like const, structures, enumerated types and more. Key concepts are presented concisely for quick reference.

Uploaded by

Shining Chris
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/ 11

C Reference Cheat Sheet

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

Number Literals Primitive Variable Types (cont)

Integers unsigned char 1 0 to 28-1

0b11111111 binary 0B11111111 binary signed char 1 -27 to 27-1

0377 octal 255 decimal int 2/4 unsigned OR signed

0xff hexadecimal 0xFF hexadecimal unsigned int 2/4 0 to 216 -1 OR 231 -1

Real Numbers signed int 2/4 -215 to 215 -1 OR -231 to 232 -1

88.0f / 88.1234567f short 2 unsigned OR signed

single precision float ( f suffix ) unsigned short 2 0 to 216 -1

88.0 / 88.123456789012345 signed short 2 -215 to 215 -1

double precision float ( no f suffix ) long 4/8 unsigned OR signed

Signage unsigned long 4/8 0 to 232 -1 OR 264 -1

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

Decl​aring Floats
int x; A variable. Type Bytes Value Range (Norma​lized)
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.
declar​ation (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.

how exciting!;  Non-alphanumeric.

iamaverylongvariablenameohmygoshyesiam; 

Longer than 31 characters (C89 & C90 only)

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


verb eg. plotRobotUprising().

Primitive Variable Types

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

[class] [qualifier] [unsigned] type/void name;

by ascending arithmetic conversion

Inte​gers

Type Bytes Value Range

char 1 unsigned OR signed

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 1 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

Primitive Variable Types (cont) Structures

Storage Classes Defi​ning

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.

extern Variable is declared by another file. Declaring

Typecasting struct strctName A variable varName as structure type


varName; strctName.
(type)a Returns a as data type.
struct strctName A strctName structure type pointer, ptrName.
char x = 1, y = 2; float z = (float) x / y;
*ptrName;
Some types (denoted with OR) are architecture dependant.
struct strctName{ type a; Shorthand for defining strctName and
type b; } varName; declaring varName as that structure type.
There is no primitive boolean type, only zero (false, 0) and non-zero (true,
usually 1.) struct strctName A variable varName as structure type
varName = { a, b }; strctName and initialising its members.

Extended Variable Types Accessing

[class] [quali​fier] type name; varName.x Member x of structure varName.

by ascending arithmetic conver​sion ptrName->x Value of structure pointer ptrName member x.

From the stdint.h Library Bit Fields

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

int16_t 2 -215 to 215 -1


Type Defini​tions
uint16_t 2 0 to 216 -1
Defining
int32_t 4 -231 to 231 -1
typedef unsigned short uint16; Abbreviating a longer type name to
uint32_t 4 0 to 232 -1 uint16.
int64_t 8 -263 to 263 -1 typedef struct structName{int a, Creating a newType from a
uint64_t 8 0 to 264 -1 b;}newType; structure.

From the stdbo​ol.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
archit​ect​ure​-in​dep​endent lengths. newType y = {0, 0}; Structure y as type newType.

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 2 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

Unions Pointers (cont)

Defining *x Value stored at that address.

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

vName.y[int] Members cannot store values concur​rently. Setting y Arrays


will corrupt x.
Decl​aring
Unions are used for storing multiple data types in the same area of
type name[int]; You set array length.
memory.
type name[int] = {x, y, z}; You set array length and initialise elements.

Enumer​ation 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 dimens​ional 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.

Evaluating *(name + int) Same as name[​int].

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 &​nam​e[i​nt].
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.

Accessing \0 Null termin​ator.

x A memory address. Strings are char arrays.

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 3 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

Strings (cont) Functions (cont)

char name[4] = "Ash"; void f(type *x); Passing a structure to function f argument x (by

is equivalent to f(structure); pointer.)

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; }

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


Escape Characters x[]; return &x; } static qualifier is necessary otherwise x won't exist
\a alarm (bell/beep) \b backspace after the function exits.

\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 delimi​ters.
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 (inte​ger) 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, "ap​p", "tw​o" and "3".
void f(type Passing an array/string to function f argument x (by pointer.)
*x); app "two 3" Two arguments, "ap​p" and "two 3".
f(array); main is the first function called when the program executes.

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 4 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

Condit​ional (Branc​hing) Iterative (Looping) (cont)

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

if(a) b; Evaluates b if a is true. OR

if(a){ b; c; } Evaluates b and c if a is true. for(int i = 0; n[i] != '\0'; i++){}(C99+)

if(a){ b; }else{ c; } Evaluates b if a is true, c otherwise. Compact increment/decrement based loop.

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

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


Iterative (Looping) Skips rest of loop contents and exits loop.
while

int x = 0; while(x < 10){ x += 2; } Console Input/​Output

Loop skipped if test condition initially false. #include <stdio.h>

int x = 0; Declare and initialise integerx. Characters

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)

{} Loop delimiters. puts("string") Prints a string to the output stream.

c++; Loop contents. Formatted Data

while(); Loop keyword and condition parenthesis. Note semicolon.

c != 'Z' Test condition.

for

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 5 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

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

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
print​f("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.

SEEK_CUR Current position in file.

File Input/​Output SEEK_END End of file.

#include <stdio.h> Utilities

Opening feof(fptr) Tests end-of-file indicator.

FILE *fptr = fopen(filename, mode); rename(strOldName, Renames a file.


strNewName)
FILE Declares fptr as a FILE type pointer (stores stream location
*fptr instead of memory location.) remove(strName) Deletes a file.

fopen() Returns a stream location pointer if successful,0 otherwise. Characters

filename String containing file's directory path & name. fgetc(fptr) Returns character read or EOF if unsucc​essful.
(safe)
mode String specifying the file access mode.
fputc(int c, fptr) Returns character written or EOF if unsucc​essful.
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-ne​gative on
success, EOF otherwise.

Formatted Data

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 6 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

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

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 Placeh​older 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.

Placeh​older 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.

%c a A character. ll Display a long long integer.

%s A String. A character string. L Display a long double float.

%p A pointer. z Display a size_t integer.

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 7 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

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

j Display a intmax_t integer. Name Reserved By Library

t Display a ptrdiff_t integer. d_... dirent.h

l_... fcntl.h
Prepro​cessor 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

​ ​ ​these delimi​ters. */ c_... termios.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

_Generic default int typedef Heap Space

_Imaginary do long union #include <stdlib.h>

_Noreturn double register unsigned Allocating

_Static_assert else restrict void malloc(); Returns a memory location if

_Thread_local enum return volatile succes​sful, NULL otherwise.

auto extern short while type *x; x = Memory for a variable.


malloc(sizeof(type));
_A-Z... __...
type *y; y = malloc(sizeof(type) Memory for an array/string.
* length );
C / POSIX Reserved Keywords
struct type *z; z = Memory for a structure.
E[0-9]... E[A-Z]... is[a-z]... to[a-z]... malloc(sizeof(struct type));
LC_[A-Z]... SIG[A-Z]... SIG_[A-Z]... str[a-z]... Deallocating
mem[a-z]... wcs[a-z]... ..._t free(ptrName); Removes the memory allocated to
GNU Reserved Names ptrName.

Reallocating

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 8 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

Heap Space (cont) The Character Type Library

realloc(ptrName, Attempts to resize the memory block assigned to #include <ctype.h>


size); ptrName. tolower(char) Lowercase char.
The memory addresses you see are from virtual memory the operating toupper(char) Uppercase char.
system assigns to the program; they are not physical addresses.
isalpha(char) True if char is a letter of the alphabet, false otherwise.

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.

isupper(char) True if char is an uppercase letter of the alphabet, false


The Standard Library otherwise.

#include <stdlib.h> isnumber(char) True if char is numerical (0 to 9) and false 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) Concat​enates 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
succes​sful, 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) Concat​enates 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.

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


security applications.

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 9 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

The String Library (cont) Unary Operators (cont)

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.

The Time Library


Binary Operators
#include <time.h>
by descending evaluation preced​ence
Variable Types
a * b; Product of a and b. (a × b)
time_t Stores the calendar time.
a / b; Quotient of dividend a and divisor b. Ensure divisor is non-zero.
struct tm *x; Stores a time & date breakdown.
(a ÷ b)
tm structure members:
a % b; Remainder of integers dividend a and divisor b.
int tm_sec Seconds, 0 to 59.
a + b; Sum of a and b.
int tm_min Minutes, 0 to 59.
a - b; Difference of a and b.
int tm_hour Hours, 0 to 23.
a << b; Left bitwise shift of a by b places. (a × 2b)
int tm_mday Day of the month, 1 to 31.
a >> b; Right bitwise shift of a by b places. (a × 2-b)
int tm_mon Month, 0 to 11.
a < b; Less than. True if a is less than b and false otherwise.
int tm_year Years since 1900.
a <= b; Less than or equal to. True if a is less than or equal to b and
int tm_wday Day of the week, 0 to 6. false otherwise. (a ≤ b)
int tm_yday Day of the year, 0 to 365. a > b; Greater than. True if a is greater than than b and false
int tm_isdst Daylight saving time. otherwise.

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)

ctime(&time_t) Returns a time_t variable as a string. a & b; Bitwise AND of a and b. (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 preced​ence a || b; Logical OR. True if either a or b are non-zero. (Logical OR) (a ⋃

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

-a Difference of 0 (zero) and a. (0 - a)

!a Complement (logical NOT) of a. (~a)

~a Binary ones complement (bitwise NOT) of a. (~a)

++a Increment of a by 1. (a = a + 1)

--a Decrement of a by 1. (a = a - 1)

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 10 of 11. https://readability-score.com
C Reference Cheat Sheet
by Ashlyn Black via cheatography.com/20410/cs/3196/

Ternary & Assignment Operators

by descending evaluation precedence

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


{ b; })

x = a; Assigns value of a to x.

a *= b; Assigns product of a and b to a. (a = a × b)

a /= b; Assigns quotient of dividend a and divisor b to a. (a = 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)

a -= b; Assigns difference of a and b to a. (a = a - b)

a <<= b; Assigns left bitwise shift of a by b places to a. (a = a × 2b)

a >>= b; Assigns right bitwise shift of a by b places to a. (a = a × 2-b)

a &= b; Assigns bitwise AND of a and b to a. (a = a ⋂ b)

a ^= b; Assigns bitwise exclus​ive-OR of a and b to a. (a = a ⊕ b)

a |= b; Assigns bitwise inclus​ive-OR of a and b to a. (a = a ⋃ b)

C Cheatsheet by Ashlyn Black

ashlynblack.com

By Ashlyn Black Published 28th January, 2015. Sponsored by Readability-Score.com


cheatography.com/ashlyn-black/ Last updated 20th April, 2015. Measure your website readability!
Page 11 of 11. https://readability-score.com

You might also like