• Advertisement
Sign in to follow this  

Handy preprocessor asserts

This topic is 4767 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, what I tried to achieve is an assert, which checks if two classes have same size. So: #if (sizeof(A) != sizeof(B)) #error ("A and B sizes differ") #endif But compiler says that sizeof(X) is not a constant, that bastard! Is there a way to go? /def

Share this post


Link to post
Share on other sites
Advertisement
#if and #error are preprocessor commands

At the time when the preprocessor is run, class definitions and so on are not known yet. So getting the size of a structure is not possible at this point.

The only way to check if the size of two classes/structures is the same is in the compilation stage, where sizeof() is available.

Check out this site:
http://www.boost.org/libs/static_assert/static_assert.htm

Share this post


Link to post
Share on other sites
#define CheckSize(x, y) do { char Tester[(sizeof(x) == sizeof(y) ? 1 : -1)]; Tester[0] = 0; } while(0)

Share this post


Link to post
Share on other sites
Quote:
Original post by nmi
Check out this site:
http://www.boost.org/libs/static_assert/static_assert.htm


Yeah, it seems to be just what I need, though it's a large lib, so I could download it in a week or so. I will try it out then. Thanks!


Quote:
Original post by antareus
#define CheckSize(x, y) do { char Tester[(sizeof(x) == sizeof(y) ? 1 : -1)]; Tester[0] = 0; } while(0)


Amazingly, it works:

#define CHECK_PREP(name, question) char name[question ? 0 : -1];
CHECK_PREP(SizesDiffers_A_B, sizeof(A) == sizeof(B))

And it gives me the name when error occures :)

Thanks!
/def

Share this post


Link to post
Share on other sites
If you happen to be programming in Windows you already have C_ASSERT which is almost indentical to your definition of CHECK_PREP.

Be sure to put parens around "question" or you could get into macro ugliness...

Share this post


Link to post
Share on other sites
Ah yes, C_ASSERT (compile-time assert) is what you want here.
I use them occasionally to check some things about the types the caller is trying to instantiate my templated functions with. i.e. some of the functions don't work with unsigned types etc.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement