Last active
December 31, 2022 14:52
-
-
Save maddouri/2eebc0a442768ccc8ddad9a24d817a6b to your computer and use it in GitHub Desktop.
Trick to print `sizeof(type)` as a compiler error
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 sizeof_as_compiler_error(type) struct sizeof__##type##__is* (*sizeof__##type)[sizeof(type)] = -1; |
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
// 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