{"id":16313422,"url":"https://github.com/alhassy/ccheatsheet","last_synced_at":"2026-04-29T00:32:27.522Z","repository":{"id":108700358,"uuid":"191664162","full_name":"alhassy/CCheatSheet","owner":"alhassy","description":"Basics of the tremendously ubiquitous C language that permeates most of computing! ","archived":false,"fork":false,"pushed_at":"2019-07-14T17:02:07.000Z","size":550,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-22T15:16:16.724Z","etag":null,"topics":["c","cheatsheet","emacs","html","pdf"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alhassy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2019-06-13T00:45:57.000Z","updated_at":"2022-09-09T23:00:22.000Z","dependencies_parsed_at":null,"dependency_job_id":"d51b599f-2c9d-48e6-af6a-a9fc18563cc0","html_url":"https://github.com/alhassy/CCheatSheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/alhassy/CCheatSheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FCCheatSheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FCCheatSheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FCCheatSheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FCCheatSheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alhassy","download_url":"https://codeload.github.com/alhassy/CCheatSheet/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alhassy%2FCCheatSheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32405901,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-28T19:38:08.556Z","status":"ssl_error","status_checked_at":"2026-04-28T19:37:55.688Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","cheatsheet","emacs","html","pdf"],"created_at":"2024-10-10T21:51:11.226Z","updated_at":"2026-04-29T00:32:27.495Z","avatar_url":"https://github.com/alhassy.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1\u003e Easily Making CheatSheets with Org-mode \u003c/h1\u003e\n\nBasics of the tremendously ubiquitous C language that permeates most of computing!\n\n**The listing sheet, as PDF, can be found\n [here](CheatSheet.pdf)**,\n while below is an unruly html rendition.\n\nThis reference sheet is built around the system\n\u003chttps://github.com/alhassy/CheatSheet\u003e.\n\n\n# Table of Contents\n\n1.  [Adminstriva](#orgd098000)\n2.  [Conditionals \u0026 Assertion-Based Testing](#org0df350e)\n3.  [Assignments](#org00e458b)\n4.  [Loops](#org526ef7a)\n5.  [Arithmetic and Logic](#org2329ca9)\n6.  [Floats \u0026 Other Types](#org9dd9f1e)\n7.  [Forming Numbers using Octal \u0026 Hexadecimal](#orgedbf9f1)\n8.  [The Preprocessor](#org1194d93)\n9.  [Pointers](#org0523ffc)\n    1.  [Pointer initialisation](#org66dba11)\n10. [Arrays and Strings and Things](#org9d91507)\n    1.  [Strings, Arrays, and Pointers](#org67c7e71)\n11. [Input \u0026#x2013;getting things *into* the machine](#orgaf270dd)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\u003ca id=\"orgd098000\"\u003e\u003c/a\u003e\n\n# Adminstriva\n\n-   All C programs consist of a series of *functions*, which have return values!\n\n-   E.g., Assignment `x = v` is the function that updates the value of name `x`\n    with the value of `v` then terminates yielding `v` as a return value.\n\n-   Semicolons act as statement *terminators* \u0026#x2014;in contrast to English,\n    wherein they are *separators*.\n\n-   C is whitespace agnostic: Newlines and arbitrary spaces don't matter, for the most part.\n\n-   *Compound statements* are formed from primitive statements by enclosing them in `{` curly braces `}`.\n    -   Compounds may appear where-ever a single statement is allowed.\n\n-   All keywords are in lowercase.\n\n-   C comments do *not* nest.\n-   Include files personal files by enclosing them in \"quotes\", use \u003cbrackets\u003e for\n    standard library files.\n-   *All* statements must terminate with a semicolon.\n-   Everything must be declared before it can be used \u0026#x2014;sequential.\n-   Characters are in-fact aliases for ASCII numerals.\n\n        printf(\"'A' ≈ %d  ≡  %s\", 'A', 'A' == 65? \"true\" : \"false\");\n        printf(\"\\n'Z' ­ 23  ≈  %c  ≡  %d\", 'Z' - 23, 'Z' - 23);\n\n    \u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n    \u003ccolgroup\u003e\n    \u003ccol  class=\"org-left\" /\u003e\n\n    \u003ccol  class=\"org-left\" /\u003e\n\n    \u003ccol  class=\"org-right\" /\u003e\n\n    \u003ccol  class=\"org-left\" /\u003e\n\n    \u003ccol  class=\"org-left\" /\u003e\n\n    \u003ccol  class=\"org-left\" /\u003e\n\n    \u003ccol  class=\"org-right\" /\u003e\n    \u003c/colgroup\u003e\n    \u003ctbody\u003e\n    \u003ctr\u003e\n    \u003ctd class=\"org-left\"\u003e'A'\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003e≈\u003c/td\u003e\n    \u003ctd class=\"org-right\"\u003e65\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003e≡\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003etrue\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003e\u0026#xa0;\u003c/td\u003e\n    \u003ctd class=\"org-right\"\u003e\u0026#xa0;\u003c/td\u003e\n    \u003c/tr\u003e\n\n\n    \u003ctr\u003e\n    \u003ctd class=\"org-left\"\u003e'Z'\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003e­\u003c/td\u003e\n    \u003ctd class=\"org-right\"\u003e23\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003e≈\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003eC\u003c/td\u003e\n    \u003ctd class=\"org-left\"\u003e≡\u003c/td\u003e\n    \u003ctd class=\"org-right\"\u003e67\u003c/td\u003e\n    \u003c/tr\u003e\n    \u003c/tbody\u003e\n    \u003c/table\u003e\n\n-   C functions don't have to return anything if it's not appropriate.\n    -   E.g., `exit(n)` is the function that returns control to the operating system;\n        passing it an argument `n`, usually 0 if everything has gone smoothly and 1 if it's\n        an error exit. Yet this function obviously' can't *return* a value.\n\n-   You must specify the type of a variable before you can use it.\n\n-   A variable name is only meaningful in the curly brackets that define it,\n    and is otherwise meaningless. This is its *scope*.\n    -   Whence, the same names can occur in different places to mean different things.\n    -   To transfer data between functions one thus uses parameter lists and return calls.\n\n-   `printf`, “print formatted”, is a *dependently-typed function*: The number and type\n    of its arguments depends on its first argument, a string.\n    -   The number of occurrences of ‘%’ in the string argument is the number of additional arguments\n        the `printf` takes.\n\n\n\u003ca id=\"org0df350e\"\u003e\u003c/a\u003e\n\n# Conditionals \u0026 Assertion-Based Testing\n\nIn C, *true ≈ non-zero*.\nForm of the conditional:\n\\vspace{-0.5em}\n\n    if (condition)\n      statementBlock\n    // The rest is optional.\n    else\n      statementBlock\n\n\\vspace{-0.5em}\n\n-   `condition` is *any* expression that returns a numeric value:\n    All numbers are treated as ‘true’, except 0 which is considered ‘false’.\n\n    \u003cdiv class=\"org-center\"\u003e\n    *Asserts are essentially compile-checked comments of user intentions!*\n    \u003c/div\u003e\n\n`assert(e)` does nothing when expression `e` is true; otherwise it gives a message\nshowing the filename, function name, line number, and the condition `e` that\nfailed to be true.\n\n    #include \u003cstdio.h\u003e\n\n    // Disable assertions at compile time by enabling NODEBUG.\n    // #define NDEBUG\n\n    #include \u003cassert.h\u003e\n    // assert(n)  ≈  if (n) {} else ⟪Terminate and display error message⟫\n\n    int sum(int n)\n    {\n      int total = 0, i = 0;\n      while (i != n + 1)\n        total += i, i++;\n\n      return total;\n    }\n\n    int main ()\n    {\n      // print-based testing\n      if (1) printf(\"here\"); else printf(\"there\");\n      printf(\"Sum of 0 + 1 + ⋯ + 99 + 100 = %d\", sum(100));\n\n      // assertion-based testing\n      assert( sum(100) == 5050 );\n      assert( (1 ? \"here\" : \"there\") == \"here\" );\n\n      // Is completely ignored if the #define is enabled.\n      // assert(0);  // Otherwise, this causes a crash.\n\n      return 0;\n    }\n\n    hereSum of 0 + 1 + ⋯ + 99 + 100 = 5050\n\n  \\vspace{-0.5em}\nEnforce a particular precedence order by enclosing expressions in parentheses.\n\n    == equals          != differs from     !  not\n    \u003e= at least        \u003c= at most          \u0026\u0026 and\n    \u003e  greater than    \u003c  less than        || or\n\n\n\u003ca id=\"org00e458b\"\u003e\u003c/a\u003e\n\n# Assignments\n\n    /* Abbreviations */\n      x ⊕= y   ≈  x = x ⊕ y\n      x++       ≈  x += 1\n      --x      ≈  x -= 1\n\nThe increment and decrement, `++/--`, operators may precede or follow a name:\n\n-   If they follow a name, then their behaviour is executed *after* the smallest context\n    \u0026#x2014;e.g., braces or conditional parentheses\u0026#x2014; in which they occur.\n\n-   When they precede a name, their behaviour is executed before the context in which\n    they appear.\n\n-   The order of evaluation is not specified inside a function call and so behaviour\n    varies between compilers.\n\n**Avoid using these in complex expressions, unless you know what you're doing.**\n\n\n\u003ca id=\"org526ef7a\"\u003e\u003c/a\u003e\n\n# Loops\n\nHere's the general form.\n\n    while (condition)\n      statementBlock\n\n    /* Abbreviations */\n    /* for      loop */   for(A; B; C;) S  ≈  A; while(B) S\n    /* do-while loop */   do S while B     ≈  S; while(B) S\n\ndo/while: The conditional is evaluated *after* the statement has been executed\nand so the statement is obeyed at least once, regardless of the truth or falsity of\nthe condition. This is useful for *do once, and possible more* operations.\n\n    int i = 0;\n    do printf(\"%d \\n\", i++);\n    while (i != 10); //Note the ending semicolon.\n\n\n\u003ca id=\"org2329ca9\"\u003e\u003c/a\u003e\n\n# Arithmetic and Logic\n\n\u003e *\u0026#x2026;and then the different branches of arithmetic \u0026#x2014;Ambition, Distraction,\n\u003e Uglification, and Derision.*\n\u003e\n\u003e \u0026#x2014;Alice's Adventures in Wonderland\n\nThe modulus operator `%` gives the *remainder* of a division.\n\n    printf(\"rem = 10 %% 3 = %d  ⇒  ∃ quot •  10 = 3 × quot + rem  ∧  quot = %d\", 10 % 3, 10 / 3);\n\n    rem = 10 % 3 = 1  ⇒  ∃ quot •  10 = 3 × quot + rem  ∧  quot = 3\n\n-   In conditionals, one may see `n % d` to mean that `n % d` is true, i.e., is *non-zero*.\n    This expresses that `n` is a *multiple* of `d`.\n\n-   That is, numerically `%` yields remainders; but logically, in C, it expresses the\n    is-multiple-of relationship.\n\nWhen `x` is a number, the shift operations correspond to multiplication and\ndivision by `2ⁿ`, respectively.\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003eLeft Shift\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`x \u003c\u003c n`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003eappend the bit representation of `x` with `n`-many 0s\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003eRight Shift\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`x \u003e\u003e n`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003ethrow away `n` bits from the end of the bit representation of `x`\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\nThe *bitwise* operators *and `\u0026`, or `|`, not `!`,* and *xor* `^` operate at the bit representation\nof an item. For example, the ASCII code of a character consists of 7 bits where\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-right\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-right\"\u003e\u003cspan class=\"underline\"\u003eBit\u003c/span\u003e\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e\u003cspan class=\"underline\"\u003eFunction\u003c/span\u003e\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-right\"\u003e7\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e0 digit, 1 letter\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-right\"\u003e6\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e0 upper case, 1 digit or lower case\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-right\"\u003e5\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e0 for a-o, 1 for digit or p-z\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\nWhence, to convert a character to uppercase it suffices to change bit 5 to be a 0\nand leave the other bits alone. That is, to perform a bitwise *and* with the binary\nnumber *11011111*, which corresponds to the decimal number 223.\n\n    // Mask, or hide, bit  6 to be a ‘1’.\n    #define toLower(c) (c | (1 \u003c\u003c 6))\n\n    #define toUpper(c) (c \u0026 223)\n\n    #define times10(x) ( (x \u003c\u003c 1)  +  (x \u003c\u003c 3)) // Parens matter!\n    // x  ⇒  2·x + 8·x  ⇒  10 · x\n\nHow did we know is was 223?\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e0. Ninth bit is on\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`100000000`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`1 \u003c\u003c 8`\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e1. Negate it: Eight ones\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`11111111`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`~(1 \u003c\u003c 8)`\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e2. Sixth bit is on\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`100000`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`1 \u003c\u003c 5`\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e3. Xor them\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`11011111`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`⋯ ^ ⋯`\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e4. See it as a decimal\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e`223`\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003e\u0026#xa0;\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\nIronically, C has no primitive binary printing utility.\n\n\n\u003ca id=\"org9dd9f1e\"\u003e\u003c/a\u003e\n\n# Floats \u0026 Other Types\n\n-   float: Representing huge numbers to tiny fractions.\n-   double: Like float, but greater precision.\n-   int: The integers; it has 2 *subtypes*; namely short, long, and unsigned.\n    -   Short and long allocate less (half) or more (twice) memory, respectively.\n    -   Unsigned means we omit negative numbers, and therefore have twice as many\n        non-negative numbers since the sign is no longer a necessary place-holder.\n        -   Also useful when negative integers are unreasonable for the current task.\n\nType aliases: `typedef existingType newName;`\n\n    // A named product: String × ℤ × ℝ   having names  name, age, height.\n    struct entry\n    {\n      char   name[30];\n      short  age;\n      float  height;\n    }; // Note that this is a statement\n\n    // Alias for readability.\n    typedef   struct entry   Person;\n\n    int main()\n    {                                            // Exponent form for numbers.\n      struct entry qasim = {\"qasim\", 0, 613e-2}; // 613e-2 ⇒ 613 × 10⁻² ⇒ 6.13\n      Person q = qasim;\n      q.age = 23;\n\n      printf(\"Hello! My name is %s and I'm %d years old, being %f ft tall\",\n         q.name, q.age, q.height);\n      return 0;\n    }\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003eHello! My name is qasim and I'm 23 years old\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003ebeing 6.130000 ft tall\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\n\n\u003ca id=\"orgedbf9f1\"\u003e\u003c/a\u003e\n\n# Forming Numbers using Octal \u0026 Hexadecimal\n\nNumbers that begin with a 0 are interpreted as octal and those beginning with 0x or 0X\nare hexadecimal. These forms are obtained from binary by grouping using 3 bits\nand 4 bits, respectively. E.g., `129 ≈ 0201 ≈ 0x81` since:\n\n-   129 →⟨binary⟩ 10 000 001 →⟨octal⟩ 2 0 1\n-   129 →⟨binary⟩ 1000 0001  →⟨hexadecimal⟩ 8 1\n\nIndeed:\n\n    int x = 129, y = 0201, z = 0x81, zz = 0X81, b = (x == y) \u0026\u0026 (x == zz);\n    printf(\"%d ≈ %d ≈ %d; %d\", x, y, z, b);\n\n    129 ≈ 129 ≈ 129; 1\n\n\n\u003ca id=\"org1194d93\"\u003e\u003c/a\u003e\n\n# The Preprocessor\n\nThe preprocessor performs alterations to a program *before* it is compiled; e.g.,\nthe following ensures the replacement of every occurrence of `this(⋯, ⋯)` after it with\nwhatever `that` is.\n\n    #define this(arg1, arg2)  that\n\n-   All preprocessor commands are preceded by the `#` symbol.\n\n-   One generally defines useful constants or abbreviations this way, and if they have\n    a collection of such parameters or utilities in some file, then they can\n    *copy-paste* them into the current program file by using `#include` as mentioned\n     before.\n\n\n\u003ca id=\"org0523ffc\"\u003e\u003c/a\u003e\n\n# Pointers\n\n-   A fly is a bug that flies; so a *fly flies*.\n-   Likewise, a *pointer points*.\n\nVariables may be used without having values declared!\nThis is akin to buying the land \u0026#x2014;computer memory\u0026#x2014; but not building the house\n\u0026#x2014;assigning a value\u0026#x2014; thereby leaving us with a vacant lot that contains trees, garbage,\nand whatever was there before you get there \u0026#x2014;as is the case in C.\n\n    char c;\n    int i;\n    long x;\n    float f;\n    double d;\n\n    // Uninitalised ⇒ have random values.\n\n    printf(\"char   %c\\n\",c);\n    printf(\"int    %i\\n\",i);\n    printf(\"long   %l\\n\",x);\n    printf(\"float  %f\\n\",f);\n    printf(\"double %d\\n\",d);\n\n\\#RESULTS:\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-right\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003echar\u003c/td\u003e\n\u003ctd class=\"org-right\"\u003e\u0026#xa0;\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003eint\u003c/td\u003e\n\u003ctd class=\"org-right\"\u003e32766\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003elong\u003c/td\u003e\n\u003ctd class=\"org-right\"\u003e\u0026#xa0;\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003efloat\u003c/td\u003e\n\u003ctd class=\"org-right\"\u003e0.0\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003edouble\u003c/td\u003e\n\u003ctd class=\"org-right\"\u003e73896\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\nRather than being set to 0, variables automatically obtain the random values in memory and\none should always initialise variables upon declaration.\n\n-   The amount of space a variable needs is its *size* in memory.\n-   The actual location of the variable in memory is called its *address* \u0026#x2014;just like the\n    address on your house or on an ugly vacant lot.\n\n-   In your computer, memory space is measured in bytes.\n    -   Not every computer uses the same storage space for its variables.\n    -   The `sizeof` keyword tells us how many bytes a variable, or structure, uses up.\n        -   Both sizeof(x) and sizeof(int) are valid calls.\n    -   This keyword is used primarily for manual allocation of memory for new variables\n        we create.\n\n            char c;\n            int i;\n            long x;\n            float f;\n            double d;\n\n            // Uninitalised ⇒ have random values.\n\n            printf(\"char   %i\\n\",sizeof(c));\n            printf(\"int    %i\\n\",sizeof(i));\n            printf(\"ℤ      %i\\n\",sizeof(int));\n            printf(\"long   %i\\n\",sizeof(x));\n            printf(\"float  %i\\n\",sizeof(f));\n            printf(\"double %i\\n\",sizeof(d));\n\n            #define Length 123\n            #define Type   char\n            Type arr[Length];\n\n            assert( sizeof(arr) == sizeof(Type) * Length );\n\n-   Memory is set aside for variables, even if they're not used.\n    -   To avoid hogging up excess memory, programs that need a lot of memory usually\n        request it a little at a time using `malloc` \u0026#x2014;‘m’emory ‘alloc’ation.\n\n-   C is a mid-level language that has the capability to examine memory and the variables\n    stored there.\n\n-   Why care about *where* variables are located in memory?\n\n    Consider sorting an array of complex data, rather than moving the data itself\n    around, it is much cheaper to simply sort an array corresponding to their numeric\n    locations in memory.\n\n    -   The variables that hold addresses are called *pointers*.\n\n-   A variable consists of 4 pieces: Name, type, size, and location in memory.\n\n    -   The first two we know, since we write them down.\n    -   The third is obtained via the `sizeof` operator.\n    -   The fourth is obtained by using the “address of” operator `\u0026`, resulting\n        in a pointer. ( One may think of ‘\u0026’ as simply projecting the fourth component\n        from a variable structure. )\n\n    *A pointer is a variable that holds a memory address.*\n\n    -   Pointers are represented as numeric locations, but they are not number values.\n\n-   `T*` is denotes pointers of type `T`.\n    -   Pointers are declared like any other variable.\n    -   Conventionally a declaration looks like `T *t;` \u0026#x2014;the whitespace around the ‘\\*’ is\n        completely irrelevant\u0026#x2014; as a reminder that the expression `*t` denotes a value of\n        type `T`. Huh?\n\n        -   Without ‘\\*’, pointers consume and represent memory locations.\n        -   With ‘\\*’, they denote a value of type `T`.\n\n        Unless you're working with pointers to pointers, you do not want\n        to write down `*p = \u0026x`, which sets the *value* at the location of `p` to refer to an *address*.\n\n    // Valid declarations\n    int*p;\n    int* q;\n    int *r;\n    int * s;\n\n    printf(\"p is location %u \\n\", p);\n\n    char arr[] = \"hello\";\n    p = \u0026arr; p = \u0026arr[0]; p = arr;\n    printf(\"p is location %u \\n\", p);\n\n    // For arrays, the array name and the address of the array both refer to the address\n    // of the zeroth element.\n    assert( \u0026arr    == arr );\n    assert( \u0026arr[0] == arr );\n\n1.  Here's some useful conversion laws\n\n    -   **\\*\u0026-inverses:** `p = \u0026x  ≡  *p = x`\n        -   The lhs lives in the land of addresses and locations,\n            whereas the rhs lives in the land of values.\n\n    -   **[]\u0026-array:** `arr + i = \u0026arr[i]`\n\n    From these we obtain:\n\n    -   **[]\\*-array:** `*(arr + i) = arr[i]`  \u0026#x2014;immediate from the above two laws.\n    -   **\\*-array:** `*arr = arr[0]`  \u0026#x2014;immediate from the above two laws.\n    -   ****\\***-array:** `**arr = arr[0][0]` \u0026#x2014;the previous law iterated twice.\n\nTips:\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-left\" /\u003e\n\n\u003ccol  class=\"org-left\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e✓\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003ePointers must be declared with the asterisk\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e✓\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003eWhen a pointer is used without its asterisk, it refers to a memory location\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e✓\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003eWhen a pointer is used with its asterisk, it indirectly refers to a value\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e✓\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003eTo assign a pointer a memory location, prefix the other variable with \u0026\u003c/td\u003e\n\u003c/tr\u003e\n\n\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003e✓\u003c/td\u003e\n\u003ctd class=\"org-left\"\u003ePointers are memory addresses and can be displayed as unsigned integers using `%u`\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\n\n\u003ca id=\"org66dba11\"\u003e\u003c/a\u003e\n\n## Pointer initialisation\n\n    int a[30], *p;\n\n    // Make p point to the beginning of the array a, since a is itself a pointer to the\n    // beginning of the array.\n    p = a;\n\n    // Determine the actual machine address of a variable by predicing it with \u0026.\n    int fred;\n    p = \u0026fred;\n\n    // If we need to know exactly where in the machine C had decidede to allocate space\n    // to fred, we need only to print out p; whence \u0026 is read “address of”.\n    printf(\"%p\", p);\n\n    0x7ffee36348ac\n\nSince the name of an array is itself a pointer to the beginning of an array, we have\n\n\u003ctable border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\"\u003e\n\n\n\u003ccolgroup\u003e\n\u003ccol  class=\"org-left\" /\u003e\n\u003c/colgroup\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd class=\"org-left\"\u003earr ≈ \u0026arr[0]\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e\n\n    // Find furthest points of ‘int a[N-1]’ that are identical.\n    #define N 12\n    int a[] = {9,8,1,2,3,4,4,3,2,1,7,6};\n\n    int * p = a, *q = \u0026a[N-1];\n    while(*p != *q) p++, q--;\n\n    assert(*p == a[2] \u0026\u0026 *q == a[9]);\n\nBefore C99, function return types could be omitted with the understanding that the\ndefault is `int`. However, `main` still needs its return type. The following works with\nmany warnings.\n\n    f() {return 9; }\n    g() {return 'c'; } // Remember that chars are actually numbers.\n\n    int main() { printf(\"%d\", f() + g()); return 0; }\n\n    108\n\n\n\u003ca id=\"org9d91507\"\u003e\u003c/a\u003e\n\n# Arrays and Strings and Things\n\n-   C arrays are homogeneous \u0026#x2014;all elements are of the same type\u0026#x2014;\n    and their size is static \u0026#x2014;one cannot readily change how many elements they contain.\n-   `T name[N]` ⇒ Declares `name` to be an array of type `T` consisting of `N` elements.\n    -   In an initialisation, `N` may be omitted and is then inferred.\n        -   E.g., `int a[] = {2, 4, 6};`\n        -   E.g., `T a[N] = {x0, ..., xM}` for `M \u003c N` initialises the first `M` elements and the\n            remaining `N - M` are uninitialised, and may consist of random junk.\n\n-   Array access and modification is done with square brackets: `arr[int_expression]`\n    may be treated as a normal variable wherever it occurs.\n\n-   Strings are just single-character arrays.\n\n    char hello  [] = \"hello\";\n    char hello1 [] = {'h', 'e', 'l', 'l', 'o', '\\0'};\n    char hello2 [6] = {'h', 'e', 'l', 'l', 'o'}; // Null byte included automatically.\n\n    // The null byte is not considered part of the string,\n    // since it's only a terminating marker.\n    // As such, it's not counted in the length of the string.\n\n    // Strings end in the null byte, 0x00 aka \\0;\n    // that's how C knows where the end of a string is;\n    // otherwise it'd keep looking for the null byte,\n    // scanning memory then crashing.\n\n    char nope [] = {'h', 'e', 'l', 'l', 'o'}; // Just an array of chars, neither size nor \\0 at the end to indicate that this is a string.\n\n    // The array name suffices to refer to the whole string,\n    // no need to mention the brackets.\n\n    // Strcmp succeeds when its arguments are different;\n    // and fails (returning 0) if they're the same.\n    #define Equal(s,t) assert(strcmp(s, t) == 0);\n\n    Equal(hello, \"hello\")\n    Equal(hello1, \"hello\")\n    Equal(hello2, \"hello\")\n\n    assert(strcmp(nope, \"hello\")); // different args.\n\n    // C stops looking when the null byte is found!\n\n    char surprise [] = \"surprise! No more, my friend\";\n    assert(strlen(surprise) == 28);\n\n    surprise[8] = '\\0';\n    Equal(surprise, \"surprise\")\n\n-   string.h contains the strX functions.\n\n-   Multi-dimensional arrays: `T arr[d1][d2]...[dN]`.\n    -   Just as chars are numbers, multi-dimensional arrays are plain one-dimensional arrays:\n        The multiple-dimension declaration syntax simply tells the compiler how to organise\n        the array into (nested) groups and the indexing tells it which (nested) group\n        we're interested in working with.\n\n    #define D0 4\n    #define D1 3\n    #define D2 2\n\n    int arr [D0][D1][D2] = // 4 groups consisting of 3 rows with 2 items in each row\n      {\n        0, 1, // Items of arr[0][0][]\n        2, 3, // Items of arr[0][1][]\n        4, 5, // Items of arr[0][2][]\n\n        // Items of arr[1][][]\n        6, 7,\n        8, 9,\n        10, 11,\n\n        // Items of arr[2][][]\n        12, 13,\n        14, 15,\n        16, 17,\n\n        // Items of arr[3][][]\n        18, 19,\n        20, 21,\n        22, 23\n      };\n\n    // Third group's second row, second item is 15.\n    assert(arr[2][1][1] == 15); // Note: 2*D0 + 1*D1 + 1*D2 ≈ (+ 8 3 2)\n\n    assert(arr[0][1][0] == 2);\n\n    int nope[2][1] = {2, 4};\n    assert( *(nope + 0) == 2);\n    // assert( *(arr + (3*D0 + 2*D1 + 2*D2)) == 15);\n\n    // Anomaly:\n    // char words [a][b][c]\n    // ⇒ has a lines, consisting of b words, where each consists of c many characters.\n\n-   The uppercase letters start at ASCII code 65 and lowercase start at code 97.\n-   The compiler sees all characters as numbers.\n\n\n\u003ca id=\"org67c7e71\"\u003e\u003c/a\u003e\n\n## Strings, Arrays, and Pointers\n\n-   The idea of a pointer is central to the C programming philosophy.\n    -   It is pointers to strings, rather than strings themselves, that're passed around\n        in a C program.\n\n-   C strings like `s = \"this\"` actually, under the hood, are *null-terminated\n    arrays of characters*: The name `s` refers to the *address of* the first character, the `'t'`,\n    with the array being `'t' → 'h' → 'i' → 's' → 𝟘`, where 𝟘 is *not* ASCII zero\n    \u0026#x2014;whose value is 48\u0026#x2014; but ASCII *null* \u0026#x2014;i.e., all bits set to 0.\n    -   Note that null 𝟘 is denoted by `'\\0'` and has *value* 0, i.e., false, so\n        conditions of the form `p != '\\0'` are the same as `p`.\n\n-   *An array name is a pointer to the beginning of the array.*\n    -   Yet, an array name is a constant and you can't do arithmetic with it.\n\n    int length(char c[]) // A string is a character array\n    {\n      // While c[l] is not an ASCII null, keep counting until.\n      int l = 0;\n      while( c[l] ) l++;\n      return l;\n    }\n\n    int main()\n    {\n      char str[] = \"hello world 0123\";\n      printf(\"length(“%s”) = %d\", str, length(str));\n       return 0;\n    }\n\n    length(“hello world 0123”) = 16\n\n-   `T *p;` ⇒ declare `p` to be a pointer to elements of type `T`.\n-   `*p = v` ⇒ “put the value of `v` in the location which `p` points to”\n\nWe can now rewrite the length function with even less square brackets.\n\n    int length(char* c)\n    {\n      char* start = c;\n      while( *c ) c++; // Local copy of c is affected.\n      return c - start;\n    }\n\n    assert(length(\"hello world\") == 11);\n\n\n\u003ca id=\"orgaf270dd\"\u003e\u003c/a\u003e\n\n# Input \u0026#x2013;getting things *into* the machine\n\n-   `getchar` returns the next character input from the keyboard.\n\n    #include \u003cstdio.h\u003e\n\n    int main()\n    {\n      printf(\"Please enter a character: \");\n      char c = getchar();\n      printf(\"You entered: %c\", c);\n      printf(\"\\nBye\\n\");\n\n      return 0;\n    }\n\nLet's extend `getchar` to work on buffers of length, say, 20:\n\n    #include \u003cstdio.h\u003e\n\n    #define BUFFER_LENGTH 10\n\n    int main()\n    {\n      printf(\"Please enter a string, only first %d chars or newline will be read: \\n\\t\\t\",\n             BUFFER_LENGTH);\n      char cs[BUFFER_LENGTH];\n      int keep_reading = 1;\n      char * p = cs;\n      while(keep_reading \u0026\u0026 p \u003c cs + BUFFER_LENGTH)\n        {*p = getchar(); if (*p == '\\n') keep_reading = 0; else p++;}\n\n      *p = '\\0'; // Strings are a null-terminated arrays of chars.\n\n      printf(\"\\nYou entered: %s\", cs);\n      printf(\"\\nBye\\n\");\n\n      return 0;\n    }\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falhassy%2Fccheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falhassy%2Fccheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falhassy%2Fccheatsheet/lists"}