(compiler used is gcc with c++17 as far as I know (difficult to find this in visual studio))
#include <iostream>
using namespace std;
void increment( int& v )
{
++v;
}
int constexpr f()
{
int v = 0;
increment( v );
return v;
}
int main( )
{
cout << f( ) << '\n';
}
The above code gives the error on compile:
constexpr function 'f' cannot result in a constant expression.
As I understand it this is because the function increment is not a constexpr. What confuses me is that the following code compiles fine:
#include <iostream>
using namespace std;
void increment( int& v )
{
++v;
}
int constexpr f()
{
int v = 0;
for( int i = 0; i < 1; ++i )
{
increment( v );
}
return v;
}
int main( )
{
cout << f( ) << '\n';
}
This code is functionally the same and it does compile, even though increment is still not a constexpr. I don't understand how it's possible that a for-loop through the range [0, 1) causes the compiler to realize that the function f actually is a constexpr.
If anyone can give some insights on constexpr in c++ and this apparent inconsistency, I'd greatly appreciate it.