Skip to content

Instantly share code, notes, and snippets.

@r-lyeh
Forked from fay59/Quirks of C.md
Created September 10, 2018 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-lyeh/4f5a8f190d8fca343bb8be09bf7ef74a to your computer and use it in GitHub Desktop.
Save r-lyeh/4f5a8f190d8fca343bb8be09bf7ef74a to your computer and use it in GitHub Desktop.
Quirks of C

Here's a list of mildly interesting things about the C language that I learned over time.

  1. Combined type and variable/field declaration, inside a struct scope: https://godbolt.org/g/Rh94Go
  2. Compound literals are lvalues: https://godbolt.org/g/Zup5ZB
  3. Switch cases anywhere: https://godbolt.org/g/fSeL18 (also see: Duff's Device)
  4. Flexible array members: https://godbolt.org/g/HCjfzX
  5. {0} as a universal initializer: https://godbolt.org/g/MPKkXv
  6. Function typedefs: https://godbolt.org/g/5ctrLv
  7. Array pointers: https://godbolt.org/g/N85dvv
  8. Modifiers to array sizes in parameter definitions: https://godbolt.org/z/SKS38s
  9. Flat initializer lists: https://godbolt.org/g/RmwnoG
  10. What’s an lvalue, anyway: https://godbolt.org/g/5echfM
  11. Void globals: https://godbolt.org/z/C52Wn2
  12. Alignment implications of bitfields: https://godbolt.org/z/KmB4CB

Special mentions:

  1. The power of UB: https://godbolt.org/g/H6mBFT. This happens because:
    1. LLVM sees that side_effects has only two possible values: NULL (the initial value) or this_is_not_directly_called_by_main (if bar is called)
    2. LLVM sees that side_effects is called, and it is UB to call a null pointer
    3. UB is impossible, so LLVM assumes that bar will have executed by the time main runs rather than face the consequences
    4. Under this assumption, side_effects is always this_is_not_directly_called_by_main.
  2. A macro that tells you if an expression is an integer constant, if you can't use __builtin_constant_p: https://godbolt.org/g/a41gmx (from Martin Uecker, on the Linux kernel ML)
  3. You can make some pretty weird stuff in C, but for a real disaster, you need C++. Labels inside expression statements in really weird places: https://godbolt.org/g/k9wDRf.

(I have a bunch of mildly interesting in C++ too, but so does literally everyone who’s used the language for more than an hour, so it’s not as interesting.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment