Okay, I've seen many posts here about odd idioms and common practices in C that might not be initially intuitive. Perhaps a few examples are in order
Elements in an array:
#define ELEMENTS(x) (sizeof (x) / sizeof (*(x)))
Odd array indexing:
a[5] = 5[a]
Single line if/else/while/for safe #defines
#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else
My question to the expert C programmers out there is: What idioms, practices, code snippits, or little known facts show up a lot in C code but might not be very intuitive but offer a good insight into C programming?
An idiom is a widely used saying or expression that contains a figurative meaning that is different from the phrase's literal meaning. For example, if you say you're feeling “under the weather,” you don't literally mean that you're standing underneath the rain.
In computer programming, a programming idiom or code idiom is a group of code fragments sharing an equivalent semantic role, which recurs frequently across software projects often expressing a special feature of a recurring construct in one or more programming languages or libraries.
The "arrow operator" for counting down from n-1
to 0
:
for ( int i = n; i --> 0; ) ...
It's not hugely common, but it's an interesting illustration that in some ways the initialize/test/update parts of a for
loop are convention. That's the usual pattern, but you can still put any arbitrary expressions in there.
It's also a nice little reminder about how lexical analysis works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With