Skip to content

Instantly share code, notes, and snippets.

@zettoone
Created November 6, 2012 06:19
Show Gist options
  • Save zettoone/4022951 to your computer and use it in GitHub Desktop.
Save zettoone/4022951 to your computer and use it in GitHub Desktop.
Typechecking macro in c
#include <stdio.h>
#define min_t(type, x, y) ({ \
type __min1 = (x); \
type __min2 = (y); \
__min1 < __min2 ? __min1: __min2; })
/* generate warning if the types are unmatched: "comparison of distinct pointer types lacks a cast" */
#define min(x, y) ({ \
typeof(x) _min1 = (x); \
typeof(y) _min2 = (y); \
(void) (&_min1 == &_min2); \
_min1 < _min2 ? _min1 : _min2; })
int main(int argc, char const *argv[])
{
int a = 12;
unsigned b = 14;
printf("min_t: %d\n", min_t(int, a, b));
printf("min: %d\n", min(a, b));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment