Skip to content

Instantly share code, notes, and snippets.

@JamesNewton
Created November 4, 2021 00:51
Show Gist options
  • Save JamesNewton/66654a601ab462a875c0db24b44dd7fc to your computer and use it in GitHub Desktop.
Save JamesNewton/66654a601ab462a875c0db24b44dd7fc to your computer and use it in GitHub Desktop.
Good C / C++ macros
//the Arduino map function.
#define MAP(x, in_min, in_max, out_min, out_max) (((x) - (in_min)) * ((out_max) - (out_min)) / ((in_max) - (in_min)) + (out_min))
#define SIGN(i) ((i)>0? 1:(i)<0?-1:0)
#define MAX(a, b) ((a)>(b)?(a):(b))
#define MIN(a, b) ((a)<(b)?(a):(b))
#define ABS(a) ((a)<0?(0-(a)):(a))
#if defined DEBUG
#define TRACE( format, ... ) printf( "%s::%s(%d)" format, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__ )
#else
#define TRACE( format, ... )
#endif
//https://stackoverflow.com/a/1772320/663416
//if x is true, y better be true. Used with assert
#define IMPLIES(x, y) (!(x) || (y))
/*
void foo(int array[], int n) {
assert(IMPLIES(n > 0, array != NULL));
...
*/
#define SWAP(x, y, T) do { T tmp = (x); (x) = (y); (y) = tmp; } while(0)
#define SORT2(a, b, T) do { if ((a) > (b)) SWAP((a), (b), T); } while (0)
//set an array (d) of size n to v
#define SET(d, n, v) do{ size_t i_, n_; for (n_ = (n), i_ = 0; n_ > 0; --n_, ++i_) (d)[i_] = (v); } while(0)
#define ZERO(d, n) SET(d, n, 0)
//calculate the number of rows in a 1 or 2 dimensional matrix
#define ROWS(x) ( sizeof(x) / sizeof(x[0]) )
//calculate the number of columns in a 2 dimensional matrix
#define COLS(x) ( sizeof(x[0]) / sizeof(x[0][0]) )
//State machine without a state variable
//https://stackoverflow.com/a/1772333/663416
#define FSM for(;;)
#define STATE(x) x##_s
#define NEXTSTATE(x) goto x##_s
/*
FSM {
STATE(s1):
... do stuff ...
NEXTSTATE(s2);
STATE(s2):
... do stuff ...
if (k<0) NEXTSTATE(s2);
// fallthrough as the switch() cases
STATE(s3):
... final stuff ...
break; // Exit from the FSM
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment