Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive variable declaration

I have just seen this black magic in folly/ManualExecutor.h

TimePoint now_ = now_.min(); 

After I grep'ed the whole library source code, I haven't seen a definition of the variable now_ anywhere else than here. What's happening here? Is this effectively some sort recursive variable declaration?

like image 569
FCR Avatar asked Dec 07 '16 13:12

FCR


People also ask

How do you declare a variable in a recursive function?

The best way to implement a variable that keeps its state between function calls is to use the static keyword. This is a much cleaner way of declaring a variable that will keep its value between calls than a global which will also pollute the global namespace unnecessarily.

What is a recursive variable?

A recursive expression contains a variable nested inside of another variable (the outer variable). The value of the outer variable is conditional based on the value of the nested variable.


2 Answers

That code is most likely equal to this:

TimePoint now_ = TimePoint::min(); 

That means, min() is a static method, and calling it using an instance is same as calling it like this, the instance is used just for determining the type. No black magic involved, that's just two syntaxes for doing the same thing.

As to why the code in question compiles: now_ is already declared by the left side of the line, so when it's used for initialization on the right side, compiler already knows its type and is able to call the static method. Trying to call non-static method should give an error (see comment of @BenVoigt below).

As demonstrated by the fact that you had to write this question, the syntax in the question is not the most clear. It may be tempting if type name long, and is perhaps justifiable in member variable declarations with initializer (which the question code is). In code inside functions, auto is better way to reduce repetition.

like image 199
hyde Avatar answered Sep 16 '22 17:09

hyde


Digging into the code shows that TimePoint is an alias for chrono::steady_clock::time_point, where min() is indeed a static method that returns the minimum allowable duration:

http://en.cppreference.com/w/cpp/chrono/time_point/min

like image 22
Mikel F Avatar answered Sep 17 '22 17:09

Mikel F