
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Stack Unwinding in C++
Here we will see what is the meaning of stack unwinding. When we call some functions, it stores the address into call stack, and after coming back from the functions, pops out the address to start the work where it was left of.
The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function.
Let us see the effect of stack unwinding through an example.
Example Code
#include <iostream> using namespace std; void function1() throw (int) { //this function throws exception cout<<"\n Entering into function 1"; throw 100; cout<<"\n Exiting function 1"; } void function2() throw (int) { //This function calls function 1 cout<<"\n Entering into function 2"; function1(); cout<<"\n Exiting function 2"; } void function3() { //function to call function2, and handle exception thrown by function1 cout<<"\n Entering function 3 "; try { function2(); //try to execute function 2 } catch(int i) { cout<<"\n Caught Exception: "<<i; } cout<<"\n Exiting function 3"; } int main() { function3(); return 0; }
Output
Entering function 3 Entering into function 2 Entering into function 1 Caught Exception: 100 Exiting function 3
Here we can see that the control stores info of function3, then enters into function2, and then into function1. After that one exception occurs, so it removes all of the information from stack, and returns back to function3 again.
- Related Articles
- Stack and the stack pointer in 8085 Microprocessor
- stack empty() and stack size() in C++ STL
- Stack in Java
- Stack in Java Programming
- Stack Class in C#
- Min Stack in Python
- Find maximum in stack in O(1) without using additional stack in C++
- Which is in More Demand: Java Full Stack or Python Full Stack
- Print stack trace in Java
- Stack ADT in Data Structures
- Validate Stack Sequences in C++
- Stack Data Structure in Javascript
- Creating a Stack in Javascript
- The Stack Class in Javascript
- Stack and Queue in C#
