I have been reading about using constexpr instead of using macros for better safety, as macros can lead to undefined behavior. However, if I have the code in the following example, is it okay to do this, and just use preprocessor if statements (#if), or should I change the macros to constexpr bool.
Here is what I wanted to do:
#if NDEBUG
#define ENABLE_VALIDATION_LAYERS 0
#else
#define ENABLE_VALIDATION_LAYERS 1
#endif
vs
#if NDEBUG
constexpr bool enable_validation_layers = false;
#else
constexpr bool enable_validation_layers = true;
#endif
Code usage right now looks like this:
//if validation layers are not enabled, the validation support does not need to be checked
#if ENABLE_VALIDATION_LAYERS
if (!CheckValidationLayerSupport()) //function that returns a bool to check if validation layers are supported
{
throw std::runtime_error("validation layers requested, but not available!");
}
#endif
Related
Please consider the following little function. It provides compiler abstraction for breaking the debugger programmatically:
inline constexpr void BreakDebug()
{
#ifdef __GNUC__
__builtin_trap();
#elif defined _MSC_VER
__debugbreak();
#endif
}
I would like to rewrite the function and replace the preprocessor instructions using C++20 code. Since __builtin_trap and __debugbreak are compiler specific and mutual exclusive, I can't use a simple if constexpr since I would get a compilation error.
Assuming I would wrap the compiler macros __GNUC__ and _MSC_VER using a constexpr enumeration constant... how could that be done?
Apparently, those builtin functions can also be turned into dependent name. I checked this here. So the usual trick that consists in making potentially ill-formed code dependent works:
enum compiler_t{
gnu,
msvc
};
inline constexpr compiler_t compiler =
#ifdef __GNUC__
compiler_t:: gnu;
#else
compiler_t:: msvc;
#endif
template <class...Args>
inline constexpr void BreakDebug(Args...args)
{
if constexpr (compiler == gnu){
__builtin_trap(args...);
} else {
__debugbreak(args...);
}
}
int main(){
BreakDebug();
return 0;
}
You only need a declaration of the function that is not called (and no definition, as it won't be called):
inline constexpr void BreakDebug()
{
#ifdef __GNUC__
constexpr bool GNU = true;
constexpr void __debugbreak();
#elif defined _MSC_VER
constexpr bool GNU = false;
constexpr void __builtin_trap();
#endif
if constexpr (GNU){
__builtin_trap();
} else {
__debugbreak();
}
}
By declaring only that function that does not exist and that you will never call, you can avoid linker errors in case the signature is not the correct one.
Is there any way to use googletest to test a function that will lead to an infinite loop? I have the following code where the assert functionality is defined:
#ifndef NDEBUG
#define ukd_assert(expr) \
((void)((expr) ? 0 : (Assert::failedAssert(), 0)))
#else // NDEBUG
#define INSTANTIATE_ASSERT(fp)
#define ukd_assert(expr) ((void)0)
#endif
volatile bool loopFlag = true;
void failedAssert( void )
{
const char *str = "Assert failed\r\n";
// now hang
while(loopFlag)
{}
}
I need googletest to run a test to check that the failedAssert function is called from the assert definition. I am using a windows 10 computer if that matters.
In my C++ code I have to execute certain code under two conditions: because of a preprocessor macro OR a boolean variable check. For example:
bool done=false;
#ifdef _DEBUG
executeDebugCode();
done=true;
#endif
if (inputParam && !done)
executeDebugCode();
Is there a way to write the above code in a more elegant way, without repeating the executeDebugCode() function call two times?
EDIT:
the executeDebugCode() function should be executed once, and if one of the two condition is met. For example a function that should be executed in DEBUG mode only, that could be set by preprocessor macro or command line parameter.
Assuming that you want to execute this code only once, if at least one of these conditions is true:
if ( inputParam
#ifdef DEBUG
|| true
#endif
)
{
executeDebugCode();
}
The form I see most for this, and which tends to work well, is do make the exact check performed depend on _DEBUG, so you'd get:
#ifdef _DEBUG
#define SHOULD_EXECUTE_DEBUG_CODE() 1
#else
#define SHOULD_EXECUTE_DEBUG_CODE() inputParam
#endif
if (SHOULD_EXECUTE_DEBUG_CODE())
executeDebugCode();
Note that if inputParam is a local variable (as Sambuca points out in the comments), this macro SHOULD_EXECUTE_DEBUG_CODE cannot be used in other functions, and for maintainability, it may be worth adding #undef SHOULD_EXECUTE_DEBUG_CODE at the end of the function to prevent accidental misuse.
How about something like this :
bool debugEnabled = inputParam;
#ifdef _DEBUG
debugEnabled = true;
#endif
if (debugEnabled)
executeDebugCode()
ie. use one flag to control the code behavior, but allow that flag to be set in different ways.
My approach would be something like this
#ifdef _DEBUG
#define SHOULD_EXECUTE 1
#else
#define SHOULD_EXECUTE 0
#endif
if (SHOULD_EXECUTE || inputParam) {
executeDebugCode();
}
This way your if-statement shows right away that you're checking on a preprocessor define and another (boolean) condition.
This will not generate any overhead in runtime if DEBUG is not enabled.
#ifdef _DEBUG
#define MY_DEBUG true
#else
#define MY_DEBUG false
#endif
if ( inputParam || MY_DEBUG )
executeDebugCode();
In the source code of stdbool.h in LLVM project, it reads:
/* Don't define bool, true, and false in C++, except as a GNU extension. */
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Define _Bool, bool, false, true as a GNU extension. */
#define _Bool bool
#define bool bool
#define false false
#define true true
#endif
In the last 4 lines there are three lines of the from #define X X. Why would you do that? What difference does it make? Wouldn't this force compiler to just replace, say, true with true?
The only reason I can think of is, that preprocessor statements like
#ifdef bool
// do some stuff or define bool
#endif
in other c files include afterwards will work proper and not trying to redefine bool in another way like
#define bool int
which would interfere with the first definition
#define X X
has the effect that "the pre-processor conditional"*:
#ifdef X
is "true" "succeeds".*
* update
It would make the difference that true, false etc are now macros. So code like this
#if defined(true)
...
#else
...
#endif
would be affected.
I can check predefined value like:
#ifdef SOME_VAR
// Do something
#elif
// Do something 2
#endif
If I have to check 2 values instead of 1. Are there any operator:
#ifdef SOME_VAR and SOME_VAR2
// ...
#endif
Or I have to write:
#ifdef SOME_VAR
#ifdef SOME_VAR2
// At least! Do something
#endif
#endif
The standard short-circuiting and operator (&&) along with the defined keyword is what is used in this circumstance.
#if defined(SOME_VAR) && defined(SOME_VAR2)
/* ... */
#endif
Likewise, the normal not operator (!) is used for negation:
#if defined(SOME_VAR) && !defined(SOME_OTHER_VAR)
/* ... */
#endif
You can use the defined operator:
#if defined (SOME_VAR) && defined(SOME_VAR2)
#endif
#ifdef and #ifndef are just shortcuts for the defined operator.
You can write:
#if defined(SOME_VAR) && defined(SOME_VAR2)
// ...
#endif
#if defined(A) && defined(B)
One alternative is to get away from using #ifdef and just use #if, since "empty symbols" evaluate to false in the #if test.
So instead you could just do
#if SOME_VAR && SOME_OTHER_VAR
// -- things
#endif
But the big side effect to that is that you not only need to #define your variables, you need to define them to be something. E.g.
#define SOME_VAR 1
#define SOME_OTHER_VAR 1
Commenting out either of those #defines will make the above #if test fail (insofar as the enclosed stuff not being evaluated; the compiler will not crash or error out or anything).