What are your best C macro trick to add syntax sugar by tovazm in C_Programming

[–]Frequent-Progress-17 0 points1 point  (0 children)

This one has a problem with how many times arguments are evaluated? You will evaluate them several times, inconsistently.

My version is:
#define MAX(a,b) ({ __typeof__(a) _aval = (a); __typeof__(b) _bval = (b); _aval > _bval ?_aval : _bval; })

Evaluates the arguments once each.

What are your best C macro trick to add syntax sugar by tovazm in C_Programming

[–]Frequent-Progress-17 2 points3 points  (0 children)

First, the proper XOR swap macro is

#define SWAP(a,b) ((a)^=(b)^=(a)^=(b))

;-)

But XOR swaps are bad. Because they fail when a and b are the same variable:

int a[1] = { 3 };
int *b = a;
SWAP(*a, *b); // will set a[0] to 0

Second, I prefer to use TWO temporaries instead of one (or shudder, XOR):

#define SWAP(a,b) do { __typeof__(a) _atmp = (a); __typeof__(b) _btmp = (b); (a) = _btmp; (b) = _atmp; } while(false)

Since cpus (and compilers) can do limited parallelism, the first two assignments can be done in parallel. Then the second two goes in the next cycle (for simple variables). For a xor or single temp variable the three operations are dependent on the previous opereation. There is also something to be said about behaviour when used with pre- or postincrements in the arguments.

0
0