We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Does anyone know how to write a compiletime ASSERT? If the condition is true, then don't generate any code. If it is false, then does #error Assert Failed to stop compilation. Thanks, Anh Something like this:
if (condition) { } else { #error Assert Failed }
You would need to use proprocessor directives:
#if condition : // do stuff... : #else #error ... #endif
Thanks Andrew, The purpose of the assert is for size checking. The size of a struct needs to be some number of bytes per spec. Something like below. #if (sizeof(struct A) == 512) #else #error ... #endif
#if (sizeof(struct A) == 512) You can't do that. The compiler can deal with sizeof, not the preprocessor.
"The purpose of the assert is for size checking." It always makes life a whole lot easier for everyone if you give the complete story up-front! As Dan says, 'sizeof' is a compiler thing - so no use in preprocessor directives. In C51, if you write
if( sizeof(struct A) == 512 )
if( sizeof(struct A) != 512 ) { printf( "structure is wrong size!" ); for( ;; ) /* hang here forever! */; } : // rest of code here :
The problem with run-time assert is that the code needs to run in order to see the problem. I searched around the web and found below. I would prefer to see a more meaningful error output (#error). Thanks, Anh --- #define BuildAssert(expr) extern char _rgcAssert[(expr)?1:-1] #define CASSERT(ex) { typedef char cassert_type[(ex) ? 1 : -1]; }
the code needs to run in order to see the problem. The code needs to run if there's no problem, too. So what's the issue? The purpose of an assertion is to make sure that the code doesn't run when the assertion is violated (which could presumably lead to all kinds of dangerous situations). As long as it's guaranteed that that an assertion failure causes some behaviour of the code that is impossible to mistake for a nicely running program, it has done its work. A simple run-time assert() should alwyas be enough to achieve that.