Programming embedded systems: Functions and the Stack

Have you witnessed your stack these days? I suggest, have you really seemed at the stack memory and observed what accurately transpires when a perform is called and afterwards returns?

Have you seen your stack recently? I mean, have you actually looked at the stack memory and observed what precisely occurs when a perform is known as and later returns? If not, you need to enjoy lesson #8 about “Functions and the Stack”:

Lesson 8 – Functions in C and the get in touch with stack

The Greatest Invention Considering the fact that Sliced Bread

The operate in C (and method, subroutine, or subprogram in other programming languages) is the solitary greatest invention in laptop or computer science. It makes plans less difficult to recognize than any other characteristic of any programming language [1].

Capabilities Hold Your Code DRY

An noticeable motive for producing a function is to stay clear of copy code, also identified as the DRY (Never Repeat By yourself) theory. You do this by separating a piece of code and offering an interface that enables you to enter (simply call) it from different destinations in the system. Of program, you’ll have to have the programming language aid to build these types of an interface and the mechanisms of contacting and returning from a operate.

The Critical Purpose of the Stack

A simple get in touch with to a functionality and return would seem very simple sufficient. The return tackle can be stored in a sign up, this kind of as the LR (link sign-up) in ARM Cortex-M. But things get complicated when the called function phone calls another operate. A single LR sign-up can not “remember” two return addresses. The option is to retail store all this kind of nested return addresses in memory — in a facts structure known as the stack. The stack can keep the two return addresses and neighborhood variables utilised inside of the capabilities.

A very good metaphor for the functionality contact stack is a stack of dishes, where you can include or take out dishes only at the current leading

Read More... Read More