Proper Use of Assert and Enforce

Dmitry Olshansky dmitry.olsh at gmail.com
Wed Mar 14 02:59:34 PDT 2012


On 14.03.2012 9:44, 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!");

A valuable trick, as enforce returns whatever passed to it or throws:

backGround  = enforce(SDL_SetVideoMode( xResolution, yResolution, 
bitsPerPixel, SDL_HWSURFACE | SDL_DOUBLEBUF), "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?

To make it real simple:
- assert on stuff you know has to be true regardless of circumstances 
and not dependent on any possible external factors.
- enforce on stuff that must be true, but in general can fail like "file 
not found", etc. and/or depends on proper state of external factors you 
can't guarantee.

Also since assert stay true if program is correct (in common sense) 
asserts are removed from release binaries.

In your case I believe enforce is justified, as capabilities of hardware 
are not in your direct control and the release version shouldn't 
segfault in the face of user.

-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list