Last active
April 16, 2023 16:27
-
-
Save imaami/b15b40e8d45ada0c968c59668e05359e to your computer and use it in GitHub Desktop.
Polish notation sizeof()
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
#include <stdint.h> | |
#include <stdio.h> | |
/** Polish notation sizeof(). */ | |
#define of_size(x) __typeof__( \ | |
_Generic((x) \ | |
, int: of_signed (x) \ | |
, unsigned: of_unsigned (x)) ) | |
#define of_signed(x) \ | |
_Generic(&(char[(x)]){0} \ | |
, char (*)[ 1]: ( int8_t) 0 \ | |
, char (*)[ 2]: ( int16_t) 0 \ | |
, char (*)[ 4]: ( int32_t) 0 \ | |
, char (*)[ 8]: ( int64_t) 0 ) | |
#define of_unsigned(x) \ | |
_Generic(&(char[(x)+5u]){0} \ | |
, char (*)[ 6]: ( uint8_t) 0 \ | |
, char (*)[ 7]: (uint16_t) 0 \ | |
, char (*)[ 9]: (uint32_t) 0 \ | |
, char (*)[13]: (uint64_t) 0 ) | |
#define info(x) \ | |
printf("%-3s%6d, %zu B\n",#x \ | |
, (int)(x), sizeof(x)) | |
int main (void) | |
{ | |
of_size(1) i8 = -1; | |
of_size(1u) u8 = -1; | |
of_size(2) i16 = -1; | |
of_size(2u) u16 = -1; | |
info(i8); // -1, 1 B | |
info(u8); // 255, 1 B | |
info(i16); // -1, 2 B | |
info(u16); // 65535, 2 B | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment