Skip to content

Instantly share code, notes, and snippets.

@jorgenpt
Last active September 1, 2023 09:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgenpt/56a81d0a04ef6bf73177 to your computer and use it in GitHub Desktop.
Save jorgenpt/56a81d0a04ef6bf73177 to your computer and use it in GitHub Desktop.
An attempt at some saner min-max-clamp macros for C and Objective-C. Require a modern compiler (C11) with support for statement expressions (Gnu11).
#pragma once
#define _CheckTypes(a,b) _Static_assert(_Generic(a, typeof (b):1, default: 0), "Mismatched types")
#define Min(a,b) \
({ \
const typeof (a) _a = (a); \
const typeof (b) _b = (b); \
_CheckTypes(_a,_b); \
(_a < _b ? _a : _b); \
})
#define Max(a,b) \
({ \
const typeof (a) _a = (a); \
const typeof (b) _b = (b); \
_CheckTypes(_a,_b); \
(_a > _b ? _a : _b); \
})
#define Clamp(x,min,max) \
({ \
const typeof (x) _x = (x); \
const typeof (min) _min = (min); \
const typeof (max) _max = (max); \
_CheckTypes(_x,_min); \
_CheckTypes(_x,_max); \
(_x > _max ? _max : (_x < _min ? _min : _x)); \
})
@sikaida
Copy link

sikaida commented Sep 1, 2023

yo cod is awsone!!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment