Skip to content

Assertions

Ravi Mohan edited this page Dec 5, 2020 · 4 revisions

Assertions are used for error detection in the code. They basically check if the programmer's assumptions are maintained in the (ever evolving) code. If not, then they

  • stop the execution of program
  • invoke the debugger (if possible)
  • print out relevant message in the console

Assertions are define by preprocessor statements such that they, usually, can be stripped in the Dist build (while being defined in Debug and Release build, see here). Karma defines assertions in the following way (see Core.h)

#ifdef KR_ENABLE_ASSERTS
	#if _MSC_VER
		#include <intrin.h>
		#define debugBreak() __debugbreak()
	#else
		#include <signal.h>
		#define debugBreak() raise(SIGTRAP)
	#endif

	#define KR_ASSERT(expr, ...) \
			if(expr){} \
			else \
			{\
				KR_ERROR("Assertion Failed: {0}. Refer file: {1}, line: {2}", __VA_ARGS__, __FILE__, __LINE__); \
				debugBreak(); \
			}
	#define KR_CORE_ASSERT(expr, ...) \
			if(expr){} \
			else \
			{\
				KR_CORE_ERROR("Assertion Failed: {0}. Refer file: {1}, line: {2}", __VA_ARGS__, __FILE__, __LINE__); \
				debugBreak(); \
			}
#else
	#define KR_ASSERT(expr, ...)
	#define KR_CORE_ASSERT(expr, ...)
#endif

As evident from premake5.lua, KR_ENABLE_ASSERTS is defined only for Debug and Release configurations. It means macros KR_ASSERT and KR_CORE_ASSERT are stripped in the Dist build.

_MSC_VER is defined for Visual Studio compiler, so on Windows platform we use the __debugbreak() which causes a breakpoint in the code, where the user will be prompted to run the debugger. For Linux, we use raise(SIGTRAP). Furthermore, we log the message using Karma's Log (wrapper around spdlog) class (see here).

For reference I recommend Travis Vroman's video and The Cherno's video.

Clone this wiki locally