Last active
September 1, 2023 09:04
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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)); \ | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yo cod is awsone!!!!!