I recently found something akin to the following lines:
#include <string>
// test if the extension is either .bar or .foo
bool test_extension(const std::string& ext) {
return ext == ".bar" || ".foo";
// it obviously should be
// return ext == ".bar" || ext == ".foo";
}
The function obviously does not do what the comment suggests. But that's not the point here. Please note that this is not a duplicate of Can you use 2 or more OR conditions in an if statement? since I'm fully aware of how you would write the function properly!
I started to wonder how a compiler might treat this snippet. My first intuition would have been that this would be compiled to return true;
basically. Plugging the example into godbolt, showed that neither GCC 9.2 nor clang 9 make this optimization with optimization -O2
.
However, changing the code to1
#include <string>
using namespace std::string_literals;
bool test_extension(const std::string& ext) {
return ext == ".bar"s || ".foo";
}
seems to do the trick since the assembly is now in essence:
mov eax, 1
ret
So my core question is: Is there something I missed that does not allow a compiler to make the same optimization on the first snippet?
1With ".foo"s
this would not even compile, since the compiler does not want to convert a std::string
to bool
;-)
Edit
The following piece of code also gets "properly" optimized to return true;
:
#include <string>
bool test_extension(const std::string& ext) {
return ".foo" || ext == ".bar";
}