Skip to content

Instantly share code, notes, and snippets.

@uecker
Forked from fay59/Quirks of C.md
Created July 28, 2021 21:42
Show Gist options
  • Save uecker/edcf9b1fae2680b624c080d964bc9df4 to your computer and use it in GitHub Desktop.
Save uecker/edcf9b1fae2680b624c080d964bc9df4 to your computer and use it in GitHub Desktop.
Quirks of C

I thought that I’d throw together the quirks of the C language that I learned about over time for all to see. Some are plain weird, some are actually kinda neat. Most are plain weird.

  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

Special mentions:

  1. The power of UB: https://godbolt.org/g/H6mBFT. This happens because:
  2. 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)
  3. LLVM sees that side_effects is called, and it is UB to call a null pointer
  4. UB is impossible, so LLVM assumes that bar will have executed by the time main runs rather than face the consequences
  5. Under this assumption, side_effects is always this_is_not_directly_called_by_main.
  6. A macro that tells you if an expression is an integer constant: https://godbolt.org/g/a41gmx (from Martin Uecker, on the Linux kernel ML)
  7. 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 weird things 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