This document provides a cheatsheet for C programming including:
1) Common string format specifiers and character escapes for printing variables.
2) Arithmetic, relational, logical, and bitwise operators.
3) Control flow structures like if/else, for loops, while loops, do-while loops, and switch statements.
4) Macros, data types, enums, arrays, pointers, and more.
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 ratings0% found this document useful (0 votes)
195 views
C Programming
This document provides a cheatsheet for C programming including:
1) Common string format specifiers and character escapes for printing variables.
2) Arithmetic, relational, logical, and bitwise operators.
3) Control flow structures like if/else, for loops, while loops, do-while loops, and switch statements.
4) Macros, data types, enums, arrays, pointers, and more.
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/ 4
C 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) i=0; %hhd||%hhi signed char • \n - newline do { printf("%d\n", i); ++i;} %hhu unsigned char • \r - carriage return while(i<10); • \t - tab For Loop %hhn signed char* • \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 <system_header.h> #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 %g || %G shortest representation of %e||%E >= Greater than or equal to 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 || Or (x || y) typedef struct { int x, y; } point_t; %a || %A hexadecimal float-point 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 ^ (Bitwise) | (Bitwise) 0 Left-pad with zeros 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 <DevynCJohnson@Gmail.com> (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 - <stdbool.h> int_fast64_t uint_fast64_t Binary 0b char16_t - <uchar.h> char32_t - <uchar.h> intptr_t uintptr_t Hexadecimal 0x char double <stdfix.h> char \u enum EOF - <stdio.h> _Fract _Accum wchar_t string L FILE - <stdio.h> fpos_t - <stdio.h> _Sat _Fract _Sat _Accum UTF-8 string u8 float imaxdiv_t - <inttypes.h> <decimal.h> 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 nullptr_t - <stddef.h> ptrdiff_t - <stddef.h> • auto - Default specifier; Local-scope unsigned U || u • extern - Lasts the whole program, block, or sig_atomic_t - <signal,h> 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 - <stddef.h> ssize_t - <stddef.h> 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 - <wchar.h> wctype_t - <wctype.h> long double L • _Thread_local - Thread-local-storage; one wchar_t - <wchar.h> __ibm128 __float80 W || w instance per thread Type Qualifiers WEOF - <wchar.h> wint_t - <wchar.h> __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- <complex.h> long long _Fract || _Sat long long llr || LLR Function-Attributes.html _Fract • alias - The function is an alias for another; complex _Complex Example: void f () __attribute__ unsigned short _Fract || _Sat unsigned uhr || ((weak, alias ("__f"))); float complex float _Complex 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 unsigned long _Fract and _Sat ulr || ULR optimizations imaginary _Imaginary • constructor - Call function before main() unsigned long _Fract 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 <stdint.h> 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 _Accum single return, and has no other effects int64_t uint64_t • returns_twice - Returns two separate values unsigned long _Accum || _Sat ulk || ULK int_least8_t uint_least8_t • 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 <DevynCJohnson@Gmail.com> (2017) More cheatsheets at DCJTech.info
C Programming Cheatsheet Type Attributes complex float-point • <locale.h> - Category macros GNU-GCC only • HC - Half Complex; 2 byte half-precision complex • <math.h> - Mathematical and trigonometric functions float-point • <monetary.h> - Monetary unit string formatting https://gcc.gnu.org/onlinedocs/gcc/Type- • SC - Single Complex; 4 byte single-precision complex • <mqueue.h> - Message queue Attributes.html float-point • <ndbm.h> - NDBM database operations • aligned - Set alignment • DC - Double Complex; 8 byte double-precision • <net/if.h> - List local network interfaces • deprecated - Emit warning msg when called complex float-point • <netdb.h> - 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 • <netinet/in.h> - Internet protocol and address family __attribute((mode(TC))) _Complex128; • TC - Tetra Complex; 16 byte tetra-precision complex definitions float-point • <netinet/tcp.h> - Additional TCP control options • packed - Members of a struct or union are • QQ - Quarter-Fractional; 1-byte • <nl_types.h> - 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 • <poll.h> - Asynchronous file descriptor multiplexing a struct or union may appear unused; i.e. the • DQ - Double-Fractional; 8-byte • <pthread.h> - API for creating and manipulating compiler will not issue warnings • TQ - Tetra-Fractional; 16-byte POSIX threads UQQ - Unsigned Quarter-Fractional; 1-byte <pwd.h> - passwd and user information access and Variable Attributes • • UHQ - Unsigned Half-Fractional; 2-byte • control GNU-GCC only • USQ - Unsigned Single-Fractional; 4-byte • <regex.h> - Regular expression matching https://gcc.gnu.org/onlinedocs/gcc/Variable- • UDQ - Unsigned Double-Fractional; 8-byte • <sched.h> - Execution scheduling Attributes.html • UTQ - Unsigned Tetra-Fractional; 16-byte • <search.h> - Search tables • aligned - Set alignment • HA - Half-Accumulator; 2-byte • <semaphore.h> - POSIX semaphores • common - Place variable in "common" • SA - Single-Accumulator; 4-byte • <setjmp.h> - Stack environment declarations storage; the common section of an object-file • DA - Double-Accumulator; 8-byte • <signal.h> - Signals • deprecated - Emit warning msg when called • TA - Tetra-Accumulator; 16-byte • <spawn.h> - Process spawning • UHA - Unsigned Half-Accumulator; 2-byte • <stdarg.h> - Handle Variable Argument List • nocommon - Allocate space for the variable • USA - Unsigned Single-Accumulator; 4-byte • <stdbool.h> - Boolean type and values directly • UDA - Unsigned Double-Accumulator; 8-byte • <stddef.h> - Standard Type Definitions • unused - Inform the compiler that members of • UTA - Unsigned Tetra-Accumulator; 16-byte • <stdint.h> - Integer Types a struct or union may appear unused, but that is • CC - Condition Code • <stdio.h> - Standard Buffered I/O fine; i.e. the compiler will not issue warnings • BLK - Block • <stdlib.h> - Standard Library Definitions • vector_size - Set the variable's size in bytes • VOID - Void • <string.h> - Several String Operations and then divide it into parts; A size of 4 and a type • P - Address mode • <strings.h> - Case-insensitive string comparisons of "char" would make the variable contain four • V4SI - Vector; 4 single integers • <stropts.h> - Stream manipulation and ioctl • V8QI - Vector; 8 single-byte integers • <sys/ipc.h> - Inter-process communication (IPC) "char" values • BND32 - 32-bit pointer bound • <sys/mman.h> - Memory management, POSIX Special Macros and Keywords • BND64 - 32-bit pointer bound Shared Memory, and Memory-mapped files • __asm__ - Inline assembly code https://gcc.gnu.org/onlinedocs/gccint/Machine-Modes.html • <sys/msg.h> - POSIX message queues • __attribute__ - Function attribute Printing Width-based Integrals • <sys/resource.h> - Resource usage, priorities, and • __auto_type - Duck typing limiting Datatype Print Macros • <sys/select.h> - Synchronous I/O multiplexing • __extension__ - Inform compiler that the • <sys/sem.h> - XSI (SysV style) semaphores following code is a GCC extension int8_t PRId8 • <sys/shm.h> - XSI (SysV style) Shared Memory • _Generic - Type-polymorphism mechanism uint8_t PRIu8 • <sys/socket.h> - Main Berkley sockets header • __GNUC__ - GNU-GCC compiler • <sys/stat.h> - File information • __label__ - Create a local label by declaring it int16_t PRId16 • <sys/statvfs.h> - Filesystem information in the beginning of the scope (__label__ label;); • <sys/time.h> - Time and date functions and structures uint16_t PRIu16 • <sys/times.h> - File access and modification times then, place the actual label where needed (label:;) uint64_t PRIu64 • <sys/types.h> - Various data-types • __restrict__ - There is only one pointer to the • <sys/uio.h> - Vectored I/O operations referenced object; Example: int FUNC(char intmax_t PRIdMAX • <sys/un.h> - Unix domain sockets *__restrict__ DATA) {} • <sys/utsname.h> - Operating system info and uname https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html int_least32_t PRIdLEAST32 • <sys/wait.h> - Status of terminated child processes &&label - Address of label • <syslog.h> - System error logging u int_fast32_t PRIuFAST32 typeof(*x) y - Declare y with x's type • <tar.h> - Magic numbers for the tar archive format Machine Modes intptr_t PRIdPTR • <termios.h> - Terminal I/O interfaces • BI - 1 Bit Replace "PRI" with "SCN" in scanf() • <tgmath.h> - Type-Generic math macros QI - Quarter Integer; 1 byte • <time.h> - Time macros • • HI - Half Integer; 2 bytes C POSIX Library • <trace.h> - Tracing of runtime behavior • <aio.h> - Asynchronous I/O • <ulimit.h> - Resource limiting (DEPRECATED; use • PSI - Partial Single Integer; 4 bytes; not all bits used • <arpa/inet.h> - Functions for manipulating numeric IP <sys/resource.h>) • SI - Single Integer; 4 bytes addresses (part of Berkeley sockets) • <unistd.h> - Various POSIX functions and constants • PDI - Partial Double Integer; 8 bytes; not all bits used • <assert.h> - Macros assertions • <utime.h> - Inode access and modification times • DI - Double Integer; 8 bytes • <complex.h> - Arithmetic with complex numbers • <utmpx.h> - User accounting database functions • TI - Tetra Integer; 16 bytes • <cpio.h> - Magic numbers for the cpio archive format • <wchar.h> - Wide-Character handling • OI - Octa Integer; 32 bytes • <dirent.h> - Functions for opening and listing • <wctype.h> - Wide-Character classification and • QF - Quarter Floating; 1 byte quarter-precision float- directories mapping utilities point • <dlfcn.h> - Dynamic linking • <wordexp.h> - Word-expansion • HF - Half Floating; 2 byte half-precision float-point • <errno.h> - Retrieving Error Number • TQF - Three Quarter Floating; 3 byte three-quarter- • <fcntl.h> - File opening, locking, and other file precision float-point operations • SF - Single Floating; 4 byte single-precision float- • <fenv.h> - Floating-Point environment point • <float.h> - Floating Types • DF - Double Floating; 8 byte double-precision float- • <fmtmsg.h> - Message display structures point • <fnmatch.h> - Filename matching • XF - Extended Floating; 12 byte extended-precision • <ftw.h> - File tree traversal float-point • <glob.h> - Pathname pattern-matching (globbing) • TF - Tetra Floating; 16 byte tetra-precision float-point • <grp.h> - User group information and control • CQI - Complex Quarter Integer; 1 byte • <iconv.h> - Codeset conversion facility • CHI - Complex Half Integer; 2 bytes • <inttypes.h> - Fixed-size integer data-types • CSI - Complex Single Integer; 4 bytes • <iso646.h> - Alternative spellings • CDI - Complex Double Integer; 8 bytes • <langinfo.h> - Language information constants • CTI - Complex Tetra Integer; 16 bytes • <libgen.h> - Pathname manipulation • COI - Complex Octa Integer; 32 bytes • <limits.h> - Implementation-defined constants • QC - Quarter Complex; 1 byte quarter-precision
Created by Devyn Collier Johnson <DevynCJohnson@Gmail.com> (2017) More cheatsheets at DCJTech.info
C Programming Cheatsheet • > - Autoincrement addressing memory long long int at least 64-bits [- Trigraphs Digraphs 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 • c - The c register Floating-Point Datatypes asm [volatile] goto ( • 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 Specify the assembler name for data: int • y - Any MMX register 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 func(int x, int y) asm ("asm_func"); • J - Integer constant in the range 0-63, for 64-bit shifts decimal64 64-bits 8 55 • 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 uint32_t Index; move • M - 0, 1, 2, or 3 (shifts for the lea instruction) Powers of Two asm ("bsfl %1, %0;" : "=r"(Index) • N - Unsigned 8-bit integer constant (for in and out 2^X Value 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 the reference 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 code performs memory reads or writes to items reference known to fit that range (for immediate operands 4 16 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 <DevynCJohnson@Gmail.com> (2017) More cheatsheets at DCJTech.info