0

Why is that a non compile time computation function “product”, can be constexpr?

#include <iostream>

constexpr int product(int x, int y) {
    return x * y;
}

int main(int argc, char* argv[]) {
    using namespace std;
    int x1, y1 = 0;
    cout << "input x1:\n";
    cin >> x1;
    cout << "input y1:\n";
    cin >> y1;
    const int a = product(x1, y1);
    cout << a << endl;
    return 0;
}
Michaelzh
  • 441
  • 5
  • 14
  • 6
    Your `product` function *is* deterministic... – Dai Sep 22 '20 at 03:43
  • No, it's effect dependent. similar as get system clock. So it's not deterministic – Michaelzh Sep 22 '20 at 03:44
  • 3
    Read what it means to be deterministic. – Passer By Sep 22 '20 at 03:47
  • As you compile this program, Run 2 it times, first: input 4,5, you get 20; Then you run it 2nd time, input 2,2 you get 4. In that sense it's not deterministic, at least it is not a compile time const. – Michaelzh Sep 22 '20 at 03:48
  • 1
    Your usage of *deterministic* is incorrect here. You mean *only known at run-time*. – cigien Sep 22 '20 at 03:49
  • 2
    Fun-fact: the word "deterministic" does not appear anywhere in the cppreference.com documentation page for `constexpr`: https://en.cppreference.com/w/cpp/language/constexpr – Dai Sep 22 '20 at 03:58
  • Unrelated to your question, but note that `int x1, y1 = 0;` only initializes `y1`. The `x1` variable stays uninitialized. And you don't need to initialize them at definition, as you do it when reading input. – Some programmer dude Sep 22 '20 at 04:07
  • thanks all I messed, the the whole program is , the function is not. I should’v asked why compile time const & constexpr. And that is the idea come up last night, but missed/messed today. It was, a mistake. – Michaelzh Sep 22 '20 at 04:09
  • @Dai Furthermore, determinism is not mentioned in the C++ standard document itself (at least my search didn't come up with anything). – eerorika Sep 22 '20 at 04:12

1 Answers1

5

A constexpr function like product can be called at run-time or at compile-time. This depends on the context in which the function is called.

Calling product with run-time values means the function will be treated as a regular run-time function.

Similarly, storing the result of the call in a non constexpr variable will also result in the function being called at run-time. (Note that storing the result in a const int variable is also considered to be a constexpr context.)

To call a constexpr function at compile time, it must be called in a context that requires compile time evaluation, with arguments that are known at compile time, and stored in a constexpr variable.

cigien
  • 57,834
  • 11
  • 73
  • 112