2

im new to programming and just start learning C++ a few weeks, im current doing the random number stuff, but i don't understand why the parameters sometime has "()" and sometime doesn't, hope someone can explain to me, thanks!.

int main()
{
    random_device rd;
    mt19937 rdn(rd()); //Why this parameter needs "()"?
    uniform_int_distribution<int> maxrd(1, 5000);
    
    int n = maxrd(rdn); //And why this parameter doesn't need "()"?

    cout << n;
};
Trong Thang
  • 33
  • 1
  • 5
  • 1
    In `rd()` we're calling the `std::random_device::operator()` and passing the returned value as an argument to `mt19937`'s constructor. This is explained in any [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Jason Aug 03 '22 at 04:00
  • Accessing the parameter value itself never requires `()`. Using `()` means invoking `operator()` on that variables (assuming the variable is of a class that has an `operator()`). – wohlstad Aug 03 '22 at 04:07
  • A side note: you `main()` should return some `int` value (since the return value is `int`, not `void`). A value of `0` indicates that `main` completed without errors. – wohlstad Aug 03 '22 at 04:09
  • It's perfectly valid to not explicitly return a value from `main`, and some prefer it this way for toy examples because it reduces clutter. The standard will return 0 in such cases. This does not apply to any other functions. Only `main`. – paddy Aug 03 '22 at 04:10
  • @paddy thanks. Good to know. However I still believe returning an explicit `0` is somewhat better practice. – wohlstad Aug 03 '22 at 04:12
  • That is a style choice and entirely down to potentially divisive personal preference. I happen to prefer omitting it, unless I'm constructing a program that intends to return actual status values. – paddy Aug 03 '22 at 04:15
  • @StephenNewell that was my mistake, sorry. – Trong Thang Aug 03 '22 at 04:42

1 Answers1

5

Case 1

mt19937 rdn(rd());

In the above statement, rd() uses(calls) the overloaded std::random_device::operator() and then the return value from that is used as an argument to mt19937's constructor.

Basically the parenthesis () is used to call the operator() of std::random_device. That is, here the parenthesis () after the rd are there because we want to pass the returned value from rd() as argument and not rd itself.

Case 2

int n = maxrd(rdn);

In the above statement, we're calling std::uniform_int_distribution::operator() which takes a Generator as argument and so we're passing rdn as an argument since rdn is already a generator.

Note here we're not using () after rdn because we want to pass rdn as argument and not the returned value from rdn().

Jason
  • 36,170
  • 5
  • 26
  • 60