This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

compile time assert

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 )
    the compiler will realise that this is either a tautology (always true) or a contradiction (always false) and either include of exclude the code unconditionally. eg,
    if( sizeof(struct A) != 512 )
    {
       printf( "structure is wrong size!" );
       for( ;; ) /* hang here forever! */;
    }
    :
    // rest of code here
    :
    This code will either work (without the overhead of the never-executed error clause) or hang immediately.

    While this doesn't quite meet your need of a compile-time check, it should do the trick!


    Some compilers (maybe even the latest C51 - I haven't tried it) will give a warning, "expression is always true/false" or similar.

  • 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.