How can I convert from degrees to radians?

Xcode 11 • Swift 5.1 or later extension BinaryInteger { var degreesToRadians: CGFloat { CGFloat(self) * .pi / 180 } } extension FloatingPoint { var degreesToRadians: Self { self * .pi / 180 } var radiansToDegrees: Self { self * 180 / .pi } } Playground 45.degreesToRadians // 0.7853981633974483 Int(45).degreesToRadians // 0.7853981633974483 Int8(45).degreesToRadians // 0.7853981633974483 … Read more

Array-size macro that rejects pointers

Linux kernel uses a nice implementation of ARRAY_SIZE to deal with this issue: #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr)) with #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0])) and #define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b)) Of course this is portable only in GNU C as it makes use of two instrinsics: typeof operator and __builtin_types_compatible_p function. Also it uses … Read more

__FILE__ macro shows full path

Try #include <string.h> #define __FILENAME__ (strrchr(__FILE__, “https://stackoverflow.com/”) ? strrchr(__FILE__, “https://stackoverflow.com/”) + 1 : __FILE__) For Windows use ‘\\’ instead of “https://stackoverflow.com/”.

Can we have recursive macros?

Macros don’t directly expand recursively, but there are workarounds. When the preprocessor scans and expands pr(5): pr(5) ^ it creates a disabling context, so that when it sees pr again: ((5==1)? 1 : pr(5-1)) ^ it becomes painted blue, and can no longer expand, no matter what we try. But we can prevent our macro … Read more

When was the NULL macro not 0?

The C FAQ has some examples of historical machines with non-0 NULL representations. From The C FAQ List, question 5.17: Q: Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types? A: The Prime 50 series used segment 07777, offset 0 for the null pointer, at least … Read more

Comma in C/C++ macro

If you can’t use parentheses and you don’t like Mike’s SINGLE_ARG solution, just define a COMMA: #define COMMA , FOO(std::map<int COMMA int>, map_var); This also helps if you want to stringify some of the macro arguments, as in #include <cstdio> #include <map> #include <typeinfo> #define STRV(…) #__VA_ARGS__ #define COMMA , #define FOO(type, bar) bar(STRV(type) \ … Read more