Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why this constexpr expression gives me an error?

In the code below, constexpr for the line 2 does not give an error, but line 1 does.

#include <iostream>

using namespace std;

class ComplexNum{
public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){}
private:
     int r,i;

};

int randGen(){
return 10;
}
constexpr int numGen(int  i,int j){
return i+j;
}
int main()
{
    
    constexpr int i=10,j=20;
    constexpr ComplexNum c3(randGen(),randGen());    //line 1
    constexpr ComplexNum c4(numGen(i,j),numGen(i,j));//line 2

   
    return 0;
}

From the knowledge I have, constexpr evaluates the expression at compile time.

Then, shouldn’t the compiler be able to evaluate the expression in line 1, because it returns a constant integer (10 in this case)?. If not, how will line 2 be okay?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The compiler can’t compile line one because randGen() is not constexpr. The compiler can’t magically tell if a function is constexpr. Maybe it looks constexpr, but you actually want it to run at runtime. For that reason, the compiler doesn’t evaluate expressions which are not marked constexpr explicitly. Do this:

#include <iostream>

using namespace std;

class ComplexNum{
public:constexpr ComplexNum(int _r=0,int _i=0):r(_r),i(_i){}
private:
     int r,i;

};

constexpr int randGen(){
return 10;
}
constexpr int numGen(int  i,int j){
return i+j;
}
int main()
{
    
    constexpr int i=10,j=20;
    constexpr ComplexNum c3(randGen(),randGen());    //line 1
    constexpr ComplexNum c4(numGen(i,j),numGen(i,j));//line 2

   
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading