assert.h
Go to the documentation of this file.
1 // ===========================================================================
2 // Copyright (c) 2011-2012 University of Pennsylvania
3 // Copyright (c) 2013-2016 Andreas Schuh
4 // All rights reserved.
5 //
6 // See COPYING file for license information or visit
7 // https://cmake-basis.github.io/download.html#license
8 // ===========================================================================
9 
10 /**
11  * @file assert.h
12  * @brief Defines macros used for assertions.
13  */
14 
15 #pragma once
16 #ifndef _BASIS_ASSERT_H
17 #define _BASIS_ASSERT_H
18 
19 
20 #include <iostream> // for the output of the error message
21 #include <cstdlib> // to terminate the program execution
22 
23 
24 #ifdef assert
25 # undef assert
26 #endif
27 #ifdef ASSERT
28 # undef ASSERT
29 #endif
30 
31 
32 /**
33  * @def assert
34  * @brief Assertion without custom message.
35  *
36  * The assertion is only checked if NDEBUG is defined.
37  *
38  * Example:
39  * @code
40  * assert(x > 0);
41  * @endcode
42  */
43 #ifndef NDEBUG
44 # define assert(condition) \
45  do { \
46  if (!(condition)) { \
47  ::std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
48  << " line " << __LINE__ << ::std::endl; \
49  ::std::exit(EXIT_FAILURE); \
50  } \
51  } while (false)
52 #else
53 # define assert(condition) do { } while (false)
54 #endif
55 
56 /**
57  * @def ASSERT
58  * @brief Assertion with custom message.
59  *
60  * The assertion is only checked if NDEBUG is defined.
61  *
62  * Example:
63  * @code
64  * ASSERT(x > 0, "Actual value of x is " << x);
65  * @endcode
66  *
67  * @sa http://stackoverflow.com/questions/3767869/adding-message-to-assert
68  */
69 #ifndef NDEBUG
70 # define ASSERT(condition, message) \
71  do { \
72  if (!(condition)) { \
73  ::std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
74  << " line " << __LINE__ << ": " << message << ::std::endl; \
75  ::std::exit(EXIT_FAILURE); \
76  } \
77  } while (false)
78 #else
79 # define ASSERT(condition, message) do { } while (false)
80 #endif
81 
82 
83 #endif // _BASIS_ASSERT_H