-2

It acts like this.

fun();//return 1;
for (int i=0;i++;i<100)
    fun();//return 2;
fun();//return 3;

I don't want to do it manually, like:

static int i=0;
fun(){return i};
main()
{
    i++;
    fun();//return 1;
    i++;
    for (int i=0;i++;i<100)
        fun();//return 2;
    i++;
    fun();//return 3;
}

New classes and static variables are allowed.

I am trying to design a cache replacement algorithm. Most of the time I use the LRU algorithm, but, if I use LRU algorithm inside a loop I would very likely get a cache thrashing.

https://en.wikipedia.org/wiki/Thrashing_(computer_science)

I need to know if I am inside a loop. Then I can use the LFU algorithm to avoid thrashing.

Community
  • 1
  • 1
iouvxz
  • 89
  • 9
  • 27
  • 4
    A function can return different values at different times. You'll have to come up with the logic of why. The how will be easy once you figure out why. – R Sahu Oct 03 '15 at 05:43
  • No ,that won't help .The only useful answer here is the __LINE__ macro .That wouldn't be a result of any kind of logic . – iouvxz Oct 03 '15 at 08:09

2 Answers2

1

An obvious way of doing this would be using the __LINE__ macro. It will return the source code line number, which will be different throughout your function.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

It is not possible within c++ for a function to know whether or not it is inside a loop 100% of the time. However, if you are happy to do some manual coding to tell the function that it is inside a loop then making use of C++'s default parameters you could simply implement a solution. For more information on default parameters see http://www.learncpp.com/cpp-tutorial/77-default-parameters/. Also, because Global variables are generally frowned upon I have placed them in a separate namespace in order to prevent clashes.

namespace global_variables {
    int i = 0;
}

int func(bool is_in_loop = false) {
if (is_in_loop)
    {
            //do_something;
            return global_variables::i;
    }

else 
    {
            //do_something_else;
            return global_variables::i++;
    }
}

int main()
{

    // Calling function outside of loop
    std::cout << func();

    // Calling function inside of loop
    for (int j=0;j<100;j++)
    {
            // is_in_loop will be overided to be true.
            std::cout << function(true);
    }

    return 0;
}
Aaron
  • 115
  • 8
silvergasp
  • 1,517
  • 12
  • 23