top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How we can force a function to be called only once.

+3 votes
76 views

How we can force a function to be called only once. I can do this using some static variable or using boost library, but is there some other way to do this as I don't want to use any of the earlier way. Function is a non member function of any class.

posted Apr 16, 2014 by Vikash Kumar Gupta

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button
As far as I know there is no way no standard way by which you can restrict a function not to be called if it is within the scope. The only way is to control by the variables (static as you pointed out), lets wait if someone else know. I am assuming it to be C problem as it is tagged as C.
Check this code if it is C++ (found it on net: http://bytes.com/topic/c/answers/753047-calling-function-only-once )

class Init
{
  public:
  Init();
};

LoopedFunc()
{
  static Init init;
}

1 Answer

0 votes

The base way is to use static variable only something like (which you have already pointed out)

MyFunc()
{
  static bool initialized = false;

  if(!initialized) {
    initialized = true;
  }
  else
  {
     // Print Error and return
     return;
  }
  ....
  ....
}

Also check this link http://stackoverflow.com/questions/4173384/how-to-make-sure-a-function-is-only-called-once

answer Apr 17, 2014 by Chahat Sharma
Similar Questions
+6 votes

For example: It returns ‘b’ when the input is “abaccdeff”.

+2 votes

What happens if do so? Or can a pointer be freed twice in C?

+4 votes

Want to extract all unique elements from a linklist which appeared only once at best possible way any pointer?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...