Usage of C Block Scope in Interrupt Handler?

Viewed 190

Is there any advantage or disadvantage of using a C block scope in a function or specifically inside an Interrupt Handler?

From the link - http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0472i/CJAIIDCG.html - Refer stack usage.

In general, you can lower the stack requirements of your program by:

  1. Writing small functions that only require a small number of variables.
  2. Avoiding the use of large local structures or arrays.
  3. Avoiding recursion, for example, by using an alternative algorithm.
  4. Minimizing the number of variables that are in use at any given time at each p oint in a function.
  5. Using C block scope and declaring variables only where they are required, so overlapping the memory used by distinct scopes.

Advantage or disadvantage in using the C block Scope is not very clear.

3 Answers

If you write:

{
    int foo[1000];
    int bar[1000];
    … code that uses foo …
    … code that uses bar …
}

then foo and bar exist for the entire block and must use different memory. (The compiler/optimizer may recogize they are not used simultaneously and arrange to use the same memory, but various things can interfere with this, so you cannot rely on it.)

If you write:

{
    {
        int foo[1000];
        … code that uses foo …
    }
    {
        int bar[1000];
        … code that uses bar …
    }
}

Then foo and bar only exist at different times, so the compiler can use the same memory for them.

This just means that the compiler can optimize the space required by the execution of a function if you limit the life-time of variables using more scopes. Considering something like

int x;
// [some code]
int y;
// [some code not using x]

The compiler must still keep x until the end of the function. If you instead structure it like this:

{
    int x;
    // [some code]
}
{
    int y;
    // [some code not using x]
}

x doesn't exist in the code using y, so the compiler may reuse the same space that was earlier occupied by x (and it is quite likely that a compiler will indeed do that).


General note: If you have to think about this in an ISR, your ISR is probably already too big. Keep ISRs as minimal and fast as possible -- e.g. enqueuing an event might be a good action for an ISR.

Related