Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Idioms and little known facts [closed]

Tags:

arrays

c

macros

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?

like image 382
Scott Avatar asked Dec 29 '09 17:12

Scott


People also ask

What is an idiom give example?

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.

What is an idiom C++?

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.


1 Answers

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.

like image 60
Boojum Avatar answered Sep 20 '22 01:09

Boojum