Skip to content

Instantly share code, notes, and snippets.

@imaami
Last active April 16, 2023 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imaami/b15b40e8d45ada0c968c59668e05359e to your computer and use it in GitHub Desktop.
Save imaami/b15b40e8d45ada0c968c59668e05359e to your computer and use it in GitHub Desktop.
Polish notation sizeof()
#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