What is a reentrant function in C/C++?


Here we will see what is the reentrant function in C or C++. One function is said to be a reentrant function if there is a provision to interrupt that function in the course of execution, then service the ISR (Interrupt Service Routine) and then resume the task. This type of functions is used in different cases like, recursions, hardware interrupt handling.

For a reentrant function there should be some properties. These are listed below −

  • This type of function will not use any global or static variable. There are no restrictions, but it is generally not advised. This is because the interrupt may change the values of global variable, so after coming back from ISR the function may get some new value, and results will be different.

  • The reentrant function should not modify its own code. We need the action of the function should remain same throughout the code.

  • Another property is the reentrant function should not call any other non-reentrant function.

Example

int x;
int my_function() {
   return x * 10;
}
int my_second_function() {
   return my_function() * 20;
}

Here these two functions are non-reentrant. The first one is using one global variable, so it is non-reentrant. The second one is calling one non-reentrant function, so these also is not reentrant function.

Example

int my_function(int x) {
   return x * 10;
}
int my_second_function(int x) {
   return my_function(x) * 20;
}

Now these two functions are reentrant functions.

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements