Skip to content

Instantly share code, notes, and snippets.

@maddouri
Last active December 31, 2022 14:52
Show Gist options
  • Save maddouri/2eebc0a442768ccc8ddad9a24d817a6b to your computer and use it in GitHub Desktop.
Save maddouri/2eebc0a442768ccc8ddad9a24d817a6b to your computer and use it in GitHub Desktop.
Trick to print `sizeof(type)` as a compiler error
#pragma once
#define sizeof_as_compiler_error(type) struct sizeof__##type##__is* (*sizeof__##type)[sizeof(type)] = -1;
// Try it online https://godbolt.org/z/hfsxEE
#define sizeof_as_compiler_error(type) struct sizeof__##type##__is* (*sizeof__##type)[sizeof(type)] = -1;
struct EmptyStruct
{
};
enum class tribool : signed char
{
Undefined = -1,
False = 0,
True = 1,
};
sizeof_as_compiler_error(bool) // sizeof == 1, printed in error: cannot initialize a variable of type 'struct sizeof__bool__is *(*)[1]' with an rvalue of type 'int'
sizeof_as_compiler_error(tribool) // sizeof == 1, printed in error: cannot initialize a variable of type 'struct sizeof__tribool__is *(*)[1]' with an rvalue of type 'int'
sizeof_as_compiler_error(int) // sizeof == 4, printed in error: cannot initialize a variable of type 'struct sizeof__int__is *(*)[4]' with an rvalue of type 'int'
sizeof_as_compiler_error(EmptyStruct) // sizeof == 1, printed in error: cannot initialize a variable of type 'struct sizeof__EmptyStruct__is *(*)[1]' with an rvalue of type 'int'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment