# Is it possible to access the iteration/step number inside a Stan program?

**URL:** <https://discourse.mc-stan.org/t/is-it-possible-to-access-the-iteration-step-number-inside-a-stan-program/1871>\
**Category:** Modeling\
**Created:** [September 13, 2017, 12:03am UTC](https://discourse.mc-stan.org/t/is-it-possible-to-access-the-iteration-step-number-inside-a-stan-program/1871 "2017-09-13T00:03:33Z")\
**Posts on this page:** 1\
**Showing post:** 23

<div class="post-metadata">

**Author:** ![Louis](https://avatars.discourse-cdn.com/v4/letter/l/ecb155/32.png) [@Louis](https://discourse.mc-stan.org/u/Louis)\
**Post date:** [May 3, 2020, 4:42pm UTC](https://discourse.mc-stan.org/t/is-it-possible-to-access-the-iteration-step-number-inside-a-stan-program/1871/23 "2020-05-03T16:42:01Z")

</div>

I also found myself wanting to access the mcmc iteration number. I found a simple way to do it, which I share here just in case it is useful to someone. What bbbales2 suggested almost works. The key idea is to call the C++ function in the generated quantities block since such block is executed only once per mcmc iteration. We can define the following two C++ functions:

```stan
static int itct = 1;
inline void add_iter(std::ostream* pstream__) {
    itct += 1;
}
inline int get_iter(std::ostream* pstream__) {
    return itct;
}

```

Then within Stan:

```stan
functions{
    void add_iter();
    int get_iter();
}
model{
    print(get_iter()); // this will return the mcmc iteration number
}
generated quantities{
    add_iter(); // increment the counter after each iteration
}

```

You place the “add\_iter()” function within the generated quantities block. Then, you can call the “get\_iter()” function in any of the other blocks whenever needed and this will return the iteration number.

If you’re running multiple chains and you would like to discriminate among chains, then you could use something like the C++ function “getpid()” to get the PID for each chain/process.

---

_[View the full topic](https://discourse.mc-stan.org/t/is-it-possible-to-access-the-iteration-step-number-inside-a-stan-program/1871)._
