On 28/11/2019 00:40, Sam wrote:
> Daniel writes:
>
>> Consider
>>
>> #include <string>
>> #include <iostream>
>>
>> int main()
>> {
>> constexpr int n = 1;
>> constexpr int m = 10;
>> std::string s = "abcd";
>>
>> if (n < m || s.empty())
>> {
>> std::cout << "ok\n";
>> }
>> }
>>
>> Is it reasonable that vs2019 produces a warning
>>
>> warning C4127: conditional expression is constant
>> consider using 'if constexpr' statement instead
>
> The compiler does not reject this code as ill-formed; and only issues a
> non-fatal diagnostic. This is entirely the compiler's prerogative.
>
> Whether this or something else is "reasonable" is often a somewhat
> subjective matter. Someone might find it reasonable, this is a suggested
> optimization.
It should not be a "suggested optimisation". If the compiler is not
generating identical code for an "if constexpr" and an "if" where the
expression happens to be known at compile time (whether it is
technically a C++ constant or not), then the compiler is doing a poor
job at optimising.
I had a check at <
https://godbolt.org> with the simpler test variation:
#include <string>
int foo()
{
constexpr int n = 1;
constexpr int m = 10;
std::string s = "abcd";
if (n < m || s.empty())
{
return 1;
}
return 0;
}
It turns out that MSVC (/O2 /Wall /std:c++17) generates a whole pile of
muck for that code. It takes about 40 lines of assembly (excluding
string library functions) while it creates and deletes the string, adds
calls to "__security_check_cookie", whatever that is. However, it
generates the same pile when "constexpr" is added. (It also generates
an extraordinary quantity of warnings from its own headers here - is
that normal for MSVC, or is it an artefact of the
godbolt.org setup or
my incomplete knowledge of MSVC command line parameters?)
gcc and clang, on the other hand generates a single "return 1;" result
whether you have "constexpr" or not. And no warnings with "-Wall -Wextra".
> Someone else may find this to be annoying. It is quite
> common to have constant expressions when doing template
> meta-programming, so the compiler's going to bark at you, now? That only
> servers as a discouragement from turning on the "treat all warning as
> fatal" prophylactic measures. That's the camp I'm in.
>
After seeing the almost endless list of warnings MSVC produced with that
test (again, let me stress this could be due to the way I used it) I can
understand that it would take a great deal of warning parameter tuning
before "treat all warnings as errors" could be considered with that
compiler.
gcc used to have a warning for when it eliminated dead code, which would
have triggered on code like this. The warning was removed long ago,
since dead code is a natural result of optimisations (especially
inter-procedural optimisations and constant and range propagations), and
lead to large amounts of false positives.