In the following code snippet, both functions perform exactly the same functionality and are logically equivalent.
constexpr char a[] = {50, 100};
bool contains_loop(char num) {
for (int i = 0; i < 2; ++ i) {
if (a[i] == num) {
return true;
}
}
return false;
}
bool contains_expanded(char num) {
return num == a[0] || num == a[1];
}
My test in godbolt shows that, in x64 MSVC 19.30 with /O2 turned on, contains_loop is not optimized to be unrolled. In the assembly code, there is still the counter, which is not in the compiled assembly code of contains_expanded.
inc rax
cmp rax, 2
In gcc -O3, they are compiled to exactly the same assembly code.
This optimization seems pretty straightforward, but I couldn't get MSVC to optimize it (automatically). What am I missing here?