assert.h
Go to the documentation of this file.
00001 /** 00002 * @file assert.h 00003 * @brief Defines macros used for assertions. 00004 * 00005 * Copyright (c) 2011, 2012 University of Pennsylvania. All rights reserved.<br /> 00006 * See https://www.cbica.upenn.edu/sbia/software/license.html or COPYING file. 00007 * 00008 * Contact: SBIA Group <sbia-software at uphs.upenn.edu> 00009 */ 00010 00011 #pragma once 00012 #ifndef _BASIS_ASSERT_H 00013 #define _BASIS_ASSERT_H 00014 00015 00016 #include <iostream> // for the output of the error message 00017 #include <cstdlib> // to terminate the program execution 00018 00019 00020 #ifdef assert 00021 # undef assert 00022 #endif 00023 #ifdef ASSERT 00024 # undef ASSERT 00025 #endif 00026 00027 00028 /** 00029 * @def assert 00030 * @brief Assertion without custom message. 00031 * 00032 * The assertion is only checked if NDEBUG is defined. 00033 * 00034 * Example: 00035 * @code 00036 * assert(x > 0); 00037 * @endcode 00038 */ 00039 #ifndef NDEBUG 00040 # define assert(condition) \ 00041 do { \ 00042 if (!(condition)) { \ 00043 ::std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \ 00044 << " line " << __LINE__ << ::std::endl; \ 00045 ::std::exit(EXIT_FAILURE); \ 00046 } \ 00047 } while (false) 00048 #else 00049 # define assert(condition) do { } while (false) 00050 #endif 00051 00052 /** 00053 * @def ASSERT 00054 * @brief Assertion with custom message. 00055 * 00056 * The assertion is only checked if NDEBUG is defined. 00057 * 00058 * Example: 00059 * @code 00060 * ASSERT(x > 0, "Actual value of x is " << x); 00061 * @endcode 00062 * 00063 * @sa http://stackoverflow.com/questions/3767869/adding-message-to-assert 00064 */ 00065 #ifndef NDEBUG 00066 # define ASSERT(condition, message) \ 00067 do { \ 00068 if (!(condition)) { \ 00069 ::std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \ 00070 << " line " << __LINE__ << ": " << message << ::std::endl; \ 00071 ::std::exit(EXIT_FAILURE); \ 00072 } \ 00073 } while (false) 00074 #else 00075 # define ASSERT(condition, message) do { } while (false) 00076 #endif 00077 00078 00079 #endif // _BASIS_ASSERT_H