Proper Use of Assert and Enforce

Suliman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 5 01:50:43 PST 2016


On Friday, 5 February 2016 at 08:45:00 UTC, Minas Mina wrote:
> On Wednesday, 14 March 2012 at 05:44:24 UTC, Chris Pons wrote:
>> I'm new, and trying to incorporate assert and enforce into my 
>> program properly.
>>
>> My question revolves around, the fact that assert is only 
>> evaluated when using the debug switch. I read that assert 
>> throws a more serious exception than enforce does, is this 
>> correct?
>>
>> I'm trying to use enforce in conjunction with several 
>> functions that initialize major components of the framework 
>> i'm using.
>>
>> However, i'm concerned with the fact that my program might 
>> continue running, while I personally would like for it to 
>> crash, if the expressions i'm trying to check fail.
>>
>> Here is what i'm working on:
>>
>> 	void InitSDL()
>> 	{
>> 		enforce( SDL_Init( SDL_Init_Everything ) > 0, "SDL_Init 
>> Failed!");
>>
>> 		SDL_WN_SetCaption("Test", null);
>>
>> 		backGround = SDL_SetVideoMode( xResolution, yResolution, 
>> bitsPerPixel, SDL_HWSURFACE | SDL_DOUBLEBUF);
>>
>> 		enforce( backGround != null, "backGround is null!");
>>
>> 		enforce( TTF_Init() != -1, "TTF_Init failed!" );
>> 	}
>>
>> Is it proper to use in this manner? I understand that I 
>> shouldn't put anything important in an assert statement, but 
>> is this ok?
>
> Use assertions when a variable's value should not depend on 
> external factors.
> For example, let's say you want to write a square root function.
> The input must be >= 0, and because this depends on external 
> factors (e.g. user input), you must check it with `enforce()`.
> The output of the function must should always be >= 0 as well, 
> but this does not depend on any external factor, so use assert 
> for it (a negative square root is a program bug).
>
> auto sqrt(float val)
> {
>     enfore(val >= 0f);
>
>     float result = ...
>     assert(result >= 0f);
>     return result;
> }

Will asserts stay after compilation in release mode?


More information about the Digitalmars-d-learn mailing list