0
votes

I am trying to compile the following C++ code (saved as example4.cpp)

#include <iostream>

using namespace std;

constexpr double nth(double x, int n);//initialization

int main()
{
double x=2;
int n=5;
nth(x,n);//Function call
return 0;
}


constexpr double nth(double x, int n)   // function definition
{
    double res = 1;
    int i = 0;
    while (i<n) {   // while-loop: do while the condition is true
         res*=x;
         ++i;
    }
cout << res;
cout << endl;
    return res;
}

This code is giving the following error:

example4.cpp: In function ‘constexpr double nth(double, int)’: example4.cpp:24:9: error: call to non-constexpr function ‘std::basic_ostream<_CharT, _Traits>::__ostream_type& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char; _Traits = std::char_traits; std::basic_ostream<_CharT, _Traits>::__ostream_type = std::basic_ostream]’ cout << res;

Can anyone please suggest?

Thank you.

1
Think of how hard it is to write to the user's console at compile time.user4581301
Consider removing the debug statements from the function and changing nth(x,n); to cout << nth(x, n) << endl;user4581301
It worked! Thank you11187162

1 Answers

5
votes

Streaming to std::cout is not allowed in a constexpr function. In fact, only a limited set of things are. Read the cppreference article on constexpr.