Programming Cheatsheet

String Format Specifiers Character Escapes %[flags][width][.precision][length]specifier • \0 - NULL Constructs %c char • \b - backspace Do-While Loop • \f - form feed (new page) %hhd||%hhi signed char i=0; • \n - newline do { printf("%\n", i); ++i;} %hhu unsigned char • \r - carriage return while(i<10); • \t - tab %hhn signed char* For Loop • \v - vertical tab for (i=0; i<10; ++i) { %lc wint_t Arithmetic Operators printf("%d\n", i); %ls wchar_t* + Addition } While Loop %s string - Subtraction register int i=0; %d || %i signed int * Multiplication while (i<10) { ++i; } If, else if, else %u unsigned int / Division if (0 == 1) { %hi short int % Modulus/Remainder register signed int ZERO = 0; } else if (8 <= 4) { %hu unsigned short int ++ Increment by 1 const float PIf = 3.14F; %hn short int* -- Decrement by 1 } else { static char SYM[3] = "π\0"; %l signed long int ++> Pre-increment and compare } %ln long int* --> Pre-decrement and compare Macros if #ifdef __linux__ %ll signed long long int Equality Operators # include "custom_header.h" %lln long long int* == Equal to # include #endif %llu unsigned long long int != Not equal to Switch-case %f || %F float or double (%F is uppercase) < Less than switch (INPUT) { case 0: break; %Lf || %Le long double > Greater than default: break; %e || %E scientific notation (mantissa/exponent) <= Less than or equal to } Ternary Operator >= Greater than or equal to %g || %G shortest representation of %e||%E int out = (input == 7 ? 5 : 3); %o octal unsigned int Logical Operators Goto Operand Meaning Example label: %x lowercase hex unsigned int goto label; %X uppercase hex unsigned int && And (x && y) Define Datatype typedef struct { int x, y; } point_t; %a || %A hexadecimal float-point || Or (x || y) typedef union __number { %ji intmax_t ! Not !(x < y) int i; double d; } number_t; %ju uintmax_t Bitwise Operators Define Enum %jn intmax_t* enum cardsuit { & AND %zi || %zu size_t || ssize_t CLUBS = 0, | OR DIAMONDS, HEARTS, SPADES %zn size_t* }; ^ Exclusive OR (XOR) %ti || %tu ptrdiff_t Variable Aliases and Constants ~ Ones Complement (NOT) const double PI = 3.14159; %tn ptrdiff_t* << Left-shift const double *ARCHIMEDES_NUM = &PI; %p pointer address extern const double PI; // In Header >> Right-shift char PI_SYM[3] = "π\0"; // Unicode %n NULL Assignment Operators char PI_UTF8[] = u8"π\0"; %% literal % char16_t PI_UTF16[] = u"π\0"; Operand Meaning Equivalent char32_t PI_UTF32[] = U"π\0"; Width and Precision = Assign None Arrays %.3f float precision of 3 (like 3.141) double num[2] = { 3.14, 5.0 }; += Add X = X + Y %4d 4 digit wide int (like 2015) unsigned int LargeArray[2][4] = { -= Subtract X = X - Y { 0, 1, 2, 3 }, { 4, 5, 6, 7 } }; %2.2f 2 digits wide and 2 precise (19.95) char words[2][] = { "BSD", "AIX" }; *= Multiply X = X * Y Flags Order of Operations /= Divide X = X / Y - Left-justify () [] -> . :: ! ~ - + * & ++ -- %= Modulus X = X % Y + Right-justify * / % + - <<= Left-shift X = X << Y SPACE Blank space << >> < <= > >= >>= Right-shift X = X >> Y # Preceded hex & octal with "0x" || "0" != == & (Bitwise) &= AND X = X & Y 0 Left-pad with zeros ^ (Bitwise) | (Bitwise) Integer from variable - printf("%d", num); |= OR X = X | Y && || (Logical) Ternary operator Save integer to variable - scanf("%d", &num); ^= XOR X = X ^ Y Save string to variable - scanf("%s", str_var); Assignment Comma Operator

Created by Devyn Collier Johnson (2017) More cheatsheets at DCJTech.info C Programming Cheatsheet

Datatypes int_fast16_t uint_fast16_t Literal Constant Prefixes NULL void int_fast32_t uint_fast32_t Octal 0 _Bool bool - int_fast64_t uint_fast64_t Binary 0b char16_t - char32_t - intptr_t uintptr_t Hexadecimal 0x char double char \u enum EOF - _Fract _Accum wchar_t string L FILE - fpos_t - _Sat _Fract _Sat _Accum UTF-8 string u8 float imaxdiv_t - UTF-16 string u int long _Decimal32 _Decimal64 UTF-32 string U long double long int _Decimal128 _Complex _Decimal32 Raw literal string R"delimiter(STRING)delimiter" long long long long int Literal Constant Suffixes Storage Classes • auto - Default specifier; Local-scope nullptr_t - ptrdiff_t - unsigned U || u • extern - Lasts the whole program, block, or sig_atomic_t - short unsigned long long ULL compilation unit; globally visible short char short int long L • register - Stored in stack or CPU-register during the code block size_t - ssize_t - float F • static - Lasts the whole program, block, or struct union double D compilation unit; private in program • typedef - Specifies a new datatype wctrans_t - wctype_t - long double L • _Thread_local - Thread-local-storage; one wchar_t - __ibm128 __float80 W || w instance per thread Type Qualifiers WEOF - wint_t - __float128 Q || q • const - Value does not change; read-only signed unsigned __ibm128 W • restrict - For the lifetime of the pointer, the object can only be accessed via the pointer signed char unsigned char _Imaginary i • volatile - Optimizing-compilers must not signed int unsigned int _Complex128 KC change • _Atomic - Objects free from data races signed long unsigned long exponent E Function Specifiers signed long int unsigned long int __Decimal32 df || DF • inline - Inline the function when compiling signed long long unsigned long long __Decimal64 dd || DD • _Noreturn - The function does not return signed long long int unsigned long long int __Decimal128 dl || DL Function Attributes (__attribute__(())) GNU-GCC only signed short unsigned short short _Fract || _Sat short _Fract HR || hr Use in function declaration (header) https://gcc.gnu.org/onlinedocs/gcc/Function- signed short int unsigned short int _Fract || _Sat _Fract R || r Attributes.html __float80 __float128 long _Fract || _Sat long _Fract lr || LR https://gcc.gnu.org/onlinedocs/gcc/Common- Function-Attributes.html long long _Fract || _Sat long long llr || LLR _Fract • alias - The function is an alias for another; complex _Complex Example: void f () __attribute__ unsigned short _Fract || _Sat unsigned uhr || float complex float _Complex ((weak, alias ("__f"))); short _Fract UHR • aligned - Set alignment double complex double _Complex unsigned _Fract || _Sat unsigned ur || UR • always_inline - Inline the function long double complex long double _Complex _Fract • cold - Unlikely to execute; used for optimizations imaginary _Imaginary unsigned long _Fract and _Sat ulr || ULR unsigned long _Fract • constructor - Call function before main() float imaginary float _Imaginary • destructor - Call function after main() unsigned long long _Fract || _Sat ullr || • deprecated - Emit warning msg when called double imaginary double _Imaginary unsigned long long _Fract ULLR • error - Emit error message when called long double imaginary long double _Imaginary short _Accum || _Sat short _Accum hk || HK • flatten - Inline all functions in the function; __attribute__((flatten)) _Complex80 _Complex128 Accum || _Sat _Accum k || K • hot - Very likely to execute; used for long _Accum || _Sat long _Accum lk || LK optimizations • nonnull - None of the input pointers are NULL intmax_t uintmax_t long long _Accum || _Sat long long llk || LLK • nothrow - The function is guaranteed not to _Accum int8_t uint8_t throw an exception unsigned short _Accum || _Sat uhk || • optimize - Set specific optimization options for int16_t uint16_t unsigned short _Accum UHK the function int32_t uint32_t unsigned _Accum || _Sat unsigned uk || UK • pure - The function accepts arguments, has single return, and has no other effects int64_t uint64_t _Accum • returns_twice - Returns two separate values int_least8_t uint_least8_t unsigned long _Accum || _Sat ulk || ULK • simd - Create multiple functions that can unsigned long _Accum process arguments using SIMD instructions int_least16_t uint_least16_t unsigned long long _Accum || _Sat ullk || • warning - Emit warning message when called int_least32_t uint_least32_t unsigned long long _Accum ULLK https://gcc.gnu.org/onlinedocs/gcc/Fixed-Point.html int_least64_t uint_least64_t int_fast8_t uint_fast8_t

Created by Devyn Collier Johnson (2017) More cheatsheets at DCJTech.info C Programming Cheatsheet

Type Attributes complex float-point • - Category macros GNU-GCC only • HC - Half Complex; 2 byte half-precision complex • - Mathematical and trigonometric functions float-point - Monetary unit string formatting https://gcc.gnu.org/onlinedocs/gcc/Type- • • SC - Single Complex; 4 byte single-precision complex• - Message queue Attributes.html float-point • - NDBM database operations • aligned - Set alignment • DC - Double Complex; 8 byte double-precision • - List local network interfaces • deprecated - Emit warning msg when called complex float-point • - Translating protocol and hostnames into • mode - Set type mode. Example: typedef • XC - Extended Complex; 12 byte extended-precision numeric addresses _Complex float complex float-point • - Internet protocol and address family __attribute((mode(TC))) _Complex128; • TC - Tetra Complex; 16 byte tetra-precision complex definitions float-point • - Additional TCP control options packed - Members of a struct or union are • • QQ - Quarter-Fractional; 1-byte • - Localization message catalog placed to minimize the memory required • HQ - Half-Fractional; 2-byte functions • unused - Inform the compiler that members of • SQ - Single-Fractional; 4-byte • - Asynchronous multiplexing a struct or union may appear unused; i.e. the • DQ - Double-Fractional; 8-byte • - API for creating and manipulating compiler will not issue warnings • TQ - Tetra-Fractional; 16-byte POSIX threads Variable Attributes • UQQ - Unsigned Quarter-Fractional; 1-byte • - passwd and user information access and • UHQ - Unsigned Half-Fractional; 2-byte control GNU-GCC only • USQ - Unsigned Single-Fractional; 4-byte • - Regular expression matching https://gcc.gnu.org/onlinedocs/gcc/Variable- • UDQ - Unsigned Double-Fractional; 8-byte • - Execution scheduling Attributes.html • UTQ - Unsigned Tetra-Fractional; 16-byte • - Search tables • aligned - Set alignment • HA - Half-Accumulator; 2-byte • - POSIX semaphores • common - Place variable in "common" • SA - Single-Accumulator; 4-byte • - Stack environment declarations storage; the common section of an object-file • DA - Double-Accumulator; 8-byte • - Signals • deprecated - Emit warning msg when called • TA - Tetra-Accumulator; 16-byte • - Process spawning • nocommon - Allocate space for the variable • UHA - Unsigned Half-Accumulator; 2-byte • - Handle Variable Argument List • USA - Unsigned Single-Accumulator; 4-byte • - Boolean type and values directly • UDA - Unsigned Double-Accumulator; 8-byte • - Standard Type Definitions • unused - Inform the compiler that members of • UTA - Unsigned Tetra-Accumulator; 16-byte • - Integer Types a struct or union may appear unused, but that is • CC - Condition Code • - Standard Buffered I/O fine; i.e. the compiler will not issue warnings • BLK - Block • - Standard Library Definitions • vector_size - Set the variable's size in bytes • VOID - Void • - Several String Operations and then divide it into parts; A size of 4 and a type • P - Address mode • - Case-insensitive string comparisons of "char" would make the variable contain four • V4SI - Vector; 4 single integers • - Stream manipulation and • V8QI - Vector; 8 single-byte integers • - Inter-process communication (IPC) "char" values • BND32 - 32-bit pointer bound • - Memory management, POSIX Special Macros and Keywords • BND64 - 32-bit pointer bound , and Memory-mapped files • __asm__ - Inline assembly code https://gcc.gnu.org/onlinedocs/gccint/Machine-Modes.html • - POSIX message queues • __attribute__ - Function attribute Printing Width-based Integrals • - Resource usage, priorities, and limiting • __auto_type - Duck typing Datatype Print Macros • __extension__ - Inform compiler that the • - Synchronous I/O multiplexing • - XSI (SysV style) semaphores following code is a GCC extension int8_t PRId8 • - XSI (SysV style) Shared Memory • _Generic - Type-polymorphism mechanism uint8_t PRIu8 • - Main Berkley sockets header • __GNUC__ - GNU-GCC compiler • - File information • __label__ - Create a local label by declaring it int16_t PRId16 • - Filesystem information • - Time and date functions and structures in the beginning of the scope (__label__ label;); uint16_t PRIu16 then, place the actual label where needed (label:;) • - File access and modification times • __restrict__ - There is only one pointer to the uint64_t PRIu64 • - Various data-types • - Vectored I/O operations referenced object; Example: int FUNC(char intmax_t PRIdMAX • - Unix domain sockets *__restrict__ DATA) {} • - Operating system info and uname https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html int_least32_t PRIdLEAST32 • - Status of terminated child processes &&label - Address of label u int_fast32_t PRIuFAST32 • - System error logging typeof(*x) y - Declare y with x's type • - Magic numbers for the tar archive format Machine Modes intptr_t PRIdPTR • - Terminal I/O interfaces • BI - 1 Bit Replace "PRI" with "SCN" in scanf() • - Type-Generic math macros • QI - Quarter Integer; 1 byte C POSIX Library • - Time macros • HI - Half Integer; 2 bytes • - Tracing of runtime behavior • - Asynchronous I/O • PSI - Partial Single Integer; 4 bytes; not all bits used • - Resource limiting (DEPRECATED; use • - Functions for manipulating numeric IP • SI - Single Integer; 4 bytes ) addresses (part of Berkeley sockets) • PDI - Partial Double Integer; 8 bytes; not all bits used • - Various POSIX functions and constants • - Macros assertions • DI - Double Integer; 8 bytes • - access and modification times • - Arithmetic with complex numbers • TI - Tetra Integer; 16 bytes • - User accounting database functions • - Magic numbers for the cpio archive format • OI - Octa Integer; 32 bytes • - Wide-Character handling • - Functions for opening and listing • QF - Quarter Floating; 1 byte quarter-precision float- • - Wide-Character classification and directories point mapping utilities • - Dynamic linking • HF - Half Floating; 2 byte half-precision float-point • - Word-expansion • - Retrieving Error Number • TQF - Three Quarter Floating; 3 byte three-quarter- • - File opening, locking, and other file precision float-point operations • SF - Single Floating; 4 byte single-precision float- • - Floating-Point environment point • - Floating Types • DF - Double Floating; 8 byte double-precision float- • - Message display structures point • - Filename matching • XF - Extended Floating; 12 byte extended-precision • - File tree traversal float-point • - Pathname pattern-matching (globbing) • TF - Tetra Floating; 16 byte tetra-precision float-point • - User group information and control • CQI - Complex Quarter Integer; 1 byte • - Codeset conversion facility • CHI - Complex Half Integer; 2 bytes • - Fixed-size integer data-types • CSI - Complex Single Integer; 4 bytes • - Alternative spellings • CDI - Complex Double Integer; 8 bytes • - Language information constants • CTI - Complex Tetra Integer; 16 bytes • - Pathname manipulation • COI - Complex Octa Integer; 32 bytes • - Implementation-defined constants • QC - Quarter Complex; 1 byte quarter-precision

Created by Devyn Collier Johnson (2017) More cheatsheets at DCJTech.info C Programming Cheatsheet

Trigraphs Digraphs • > - Autoincrement addressing memory long long int at least 64-bits [- operand 922337203685 ??= # <: [ • r - General register 4775808, ??/ \ :> ] • i - Immediate integer operand (constant) 922337203685 4775807] • n - Immediate integer operand (static constant) ??' ^ <% { [0, • I-P - Machine-dependent immediate integers ??( [ %> } 184467440737 • E - Immediate float operand 09551615] ??) ] %: # • F - Immediate double or vector operand int128_t 128-bits [- ??! | • G, H - Machine-dependent float-operand 170141183460 • s - Non-explicit immediate integer 469231731687 ??< { • g - Register, memory, or immediate integer 303715884105 ??> } operand 728, 170141183460 • X - Any operand ??- ~ 469231731687 • 0-9 - Specific operand (i.e. r12) 303715884105 Inline Assembly • p - Memory address operand 727] asm [volatile] ( Inline x86 Assembly Modifiers uint128_t 128-bits [0, { dialect0 | dialect1 | dialect2... } • R - Legacy register : OutputOperands 340282366920 • q - Any register accessible as rl 938463463374 [ : InputOperands [ : Clobbers ] ] • Q - Any register accessible as rh 607431768211 ); // Supported x86 dialects - ("att", "intel") • a - The a register 456] • b - The b register Floating-Point Datatypes asm [volatile] goto ( • c - The c register • d - The d register Type Size Exponent Significand { dialect0 | dialect1 | dialect2... } • S - The si register : InputOperands float 32-bits 8 24 • D - The di register : Clobbers • A - The a & d registers double 64-bits 11 53 : GotoLabels • f - Any 80387 floating-point (stack) register long double 80-bits 15 64 ); // volatile disables some optimizations • t - Top of 80387 floating-point stack (%st(0)) • u - %st(1) Quadruple 128-bits 15 113 • y - Any MMX register Specify the assembler name for data: int Octuple 256-bits 19 237 • x - Any SSE register var_name asm ("asm_name") = 2; • Yz - First SSE register (%xmm0) decimal32 32-bits 6 25 Specify the assembler name for functions: int • I - Integer constant in the range 0-31, for 32-bit shifts decimal64 64-bits 8 55 func(int x, int y) asm ("asm_func"); • J - Integer constant in the range 0-63, for 64-bit shifts • K - Signed 8-bit integer constant decimal128 128-bits 12 115 uint32_t Mask = 1234; • L - 0xFF or 0xFFFF, for andsi as a zero-extending NOTE: The number of significand bits is implicit move uint32_t Index; Powers of Two asm ("bsfl %1, %0;" • M - 0, 1, 2, or 3 (shifts for the lea instruction) 2^X Value : "=r"(Index) • N - Unsigned 8-bit integer constant (for in and out instructions) : "r"(Mask) 0 1 • G - Standard 80387 floating point constant : "cc"); • C - SSE constant zero operand 1 2 Clobber Arguments • e - 32-bit signed integer constant, or a symbolic 2 4 cc - Indicates that the assembler code modifies thereference known to fit that range (for immediate operands flags register in sign-extending x86-64 instructions) 3 8 memory - Informs the compiler that the assembly • Z - 32-bit unsigned integer constant, or a symbolic 4 16 code performs memory reads or writes to items reference known to fit that range (for immediate operands other than those listed in the input and output in zero-extending x86-64 instructions) 5 32 operands https://gcc.gnu.org/onlinedocs/gcc/Machine- Inline Assembly Modifiers Constraints.html 6 64 • = - Write Datatype Limits 7 128 • + - Read & write char Smallest [-128, 127] 8 256 • & - Early clobber read & write addressable unit [0, 255] • % - Commutative; Only read-only operands 9 512 can use "%" short int at least 16-bits [-32768, 32767] 10 1024 • # - Ignored as a constraint [0, 65535] 11 2048 • * - Ignored as a register preference • ? - Slightly disparage constraint int at least 16-bits [-32768, 12 4096 32767] • ! - Severely disparage constraint [0, 65535] 13 8192 • ^ - Like "?", but only if operand needs reload • $ - Like "!", but only if operand needs reload long int at least 32-bits [-2147483648, 14 16384 2147483647] • m - Memory operand 15 32768 [0, • o - Offsetable memory operand 4294967295] 16 65536 • V - Non-offsetable memory operand • < - Autodecrement addressing memory operand

Created by Devyn Collier Johnson (2017) More cheatsheets at DCJTech.info