3

This blog does not recommend it: http://blog.kalmbachnet.de/?postid=78

But I want to do it anyway. I suppose I need to wrap my Debug.Assert with some sort of #if or #ifdef or something like that. Also, does anyone have a good example of a Debug.Assert in C++ CLI?

Suppose I have the following variable: String^ validationError = bldError.ToString(); And now I wish to do something like:

#if (DEBUG)
Debug.Assert(false, "Got the following validation error:" + validationError);
#endif

How can I do it safely in C++ CLI, and are there additional gotchas to check for?

EDIT: Based on the answers, I have come up with the following macro:

#ifdef _DEBUG
#define CLIASSERT(condition, ...) System::Diagnostics::Debug::Assert(condition, ##__VA_ARGS__)
#else
#define CLIASSERT(condition, ...) // This macro will completely evaporate in Release.
#endif

And here is an example of usage:

String^ strValidationError = bldError.ToString();
CLIASSERT(false, L"Schema validation error: " + strValidationError);
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Hamish Grubijan
  • 10,562
  • 23
  • 99
  • 147

3 Answers3

5

The blog post is accurate. Make it look like this:

#ifdef _DEBUG
    Debug::Assert(...);
#endif
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
3

Pick one

#ifndef NDEBUG // or
#if !defined(NDEBUG) // or

#ifdef _DEBUG // or
#if defined(_DEBUG)

AFAIK NDEBUG is defined in the ISO C++ standard (also used to enable/disable the standard library's assert macro), whereas _DEBUG is Microsoft-specific.

(Of course C++/CLI is not ISO C++, but in this case it doesn't make a difference)

Paul Groke
  • 6,259
  • 2
  • 31
  • 32
  • Thanks, I am a bit confused about NDEBUG. Do you have further references, as pertains to C++ CLI (a .Net language by Microsoft)? – Hamish Grubijan Sep 28 '10 at 20:57
  • The C++/CLI language is an extension to ISO/IEC C++ (see the C++/CLI standard aka. ECMA-372, chapter "1. Scope"). Now, the ISO/IEC C++ standard doesn't define the term "debug" or "debug build" in any way, but it does say that the effect of including or does depend on the presence of a macro called NDEBUG. And since the standard library header files use "!defined(NDEBUG)", it should be the safest thing to use. Of course you can use just *any* macro you like, if you make sure it's always defined/not-defined properly for the type of build you're doing. – Paul Groke Sep 28 '10 at 21:55
2

MS has documented this behaviour at http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx -- put briefly, when you do a release build, a compiler may or may not disable Assert and other such methods marked with ConditionalAttribute. For example the C# compiler does disable them, C++/CLI compiler does not. Even though the blog post is fairly old, I'd find it unlikely that the situation would change, considering what it says at that MSDN page.

Niko Kiirala
  • 194
  • 3