0

Please see this code snippet. Why it is getting compiled and generating output when the value of k is decided at the runtime?

#include <iostream>

using namespace std;

constexpr auto calcfactorialcompiletime(int k) {
    int ans = 1;
    for( int i=1; i <=k; ++i) {
        ans = ans*i;

    }
    return ans;
}

int main() {

    int k;
    cin>>k;
    const auto ans = calcfactorialcompiletime(k);  
    cout<<ans;
    //ans = 9;
    return 0;

}
nerdy_me
  • 451
  • 1
  • 5
  • 7
  • After checking "Related" list, it seems that this one suits this better: https://stackoverflow.com/questions/14116003/difference-between-constexpr-and-const?rq=1 – R2RT Aug 23 '19 at 07:55
  • The `constexpr` for a function only requires that this function must be evaluable at compile time if the passed arguments are known. So `cin>>k` **within** the `constexpr` would be forbidden. – t.niese Aug 23 '19 at 07:58
  • `constexpr` (confusingly, but from a standard writing perspective understandably) means "there exist arguments for which this function produces a constant expression", not "this function will always return a constant expression". – Max Langhof Aug 23 '19 at 08:13
  • Also, what's with the close votes not working? – Max Langhof Aug 23 '19 at 08:14
  • @t.niese True, but there was a close vote before I voted and afterwards it still only displayed one close vote... Probably just caching or so but still confused me. – Max Langhof Aug 23 '19 at 08:28
  • 1
    @MaxLanghof I would guess `R2RT` removed the close vote for the first dup because it did not match. Maybe at the same time when you added your close vote. – t.niese Aug 23 '19 at 08:29
  • also, question sounds like OP is confused by const in main() too. Local `const` variables are just that - variables, which cannot be changed after initialization. Their initialization happens before first use in scope – Swift - Friday Pie Aug 23 '19 at 08:37

0 Answers0