简体   繁体   中英

Will a modern C++ compiler optimize away false constexpr conditionals?

All throughout my code I have debugging conditionals in the form of:

if (Globals::DEBUG_MODE) std::cout << "debugging info" << std::endl;

DEBUG_MODE is a constexpr bool in a global constants header file.

My question is, when I get ready to release my software and I do some final optimizations, can I just turn that DEBUG_MODE bool off and the compiler will remove all those conditionals since they evaluate to false during compile time? Or, if I want the most optimized release code, do I need to comment out or delete those lines entirely?

I am using Visual Studio 2019 community and compiling for x64 but I want to know the answer more generally because I plan on compiling on multiple platforms. Thank you in advance.

If by discard, you mean remove from the final output binary, yes, most compilers will do that optimization ( Dead code elimination ) for if and better yet, if constexpr . Do verify that with your compiler-generated asm if you want to be sure. However, if you're planning on having code that will not compile in release mode, then no. Regular if won't do and if constexpr will do only sometimes in templates. For that to work out, you can use pre-processor directives like #ifdef DEBUG .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM