C Idioms and little-known facts

Well, I saw a lot of posts about odd idioms and common practices in C that can't be intuitive at first. Perhaps a few examples are fine

Elements in the 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 C programming experts: idioms , practices , code snippets or little-known facts show a lot in C code, but may not be very intuitive, but offer a good understanding of C programming?

+7
c macros arrays
source share
3 answers

"Arrow operator" for counting from n-1 to 0:

 for ( int i = n; i --> 0; ) ... 

This is not very common, but it is an interesting illustration that, in a sense, the parts of initializing / testing / updating the for loop are conditional. This is a regular template, but you can still place any arbitrary expressions.

It is also a small reminder of how lexical analysis works.

+11
source share

Since someone mentions this, this may be for me: Duff Device . This is a good illustration of how shortcuts work in C, and understanding this gave me an โ€œaha experienceโ€ for the first time. This is its original code:

 send(to, from, count) register short *to, *from; register count; { register n=(count+7)/8; switch(count%8){ case 0: do{ *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; }while(--n>0); } } 

Today you cannot use register and avoid defining an old-style function.

+5
source share

The well-documented comma operator (K & R, etc.) is presented in a fairly large algorithmic code and is often a surprise to many programmers who have not seen this before. It is often used to simplify some loop designs:

 #define kITERATIONS_MAX 10 int i=0,j=0,array[kITERATIONS_MAX],outArray[kITERATIONS_MAX],temp=0; for (i=0,j=kITERATIONS_MAX-1; i < kITERATIONS_MAX; i++,j--) { temp = array[i]*array[j]; outArray[i]=temp; } 

The above code will multiply the elements of the array from 0 to 9 from 9 to 0, avoiding nested loops.

When using the comma operator, both the first and second expressions are evaluated. The result of the first expression is ignored and the result of the second expression is returned.

+4
source share

All Articles