Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Monday, November 15, 2021

(C++) How to pass a variable type to a function

 E.g If you need to pass info like this:

void foo(type){
    // Other actions based on type
    cout << sizeof(type);
}

This cannot be done i.e. the type cannot be passed as a parameter since it is not a object and they do not exist at run time. They are only used by the compiler for type information building into the code. This can be instead fullfilled by templatinzing the function.

A template behaves in the following way:

template <typename T>

void foo(other_args) {

    // Other relevant data.

    T  somevar;

    cout << sizeof(somevar) << "    " <<sizeof(T);

}

Typenames can be also used to templatize classes in a similar fashion. 



Monday, May 3, 2021

Linux: Why do we need an executable stack with nested functions in GCC

 

  • The stack needs to be writable because the trampoline code is written on the stack which needs to be executed (to jump to the nested function). 
A nested function has no linkage by itself. So the trampoline code actually ensures two things:
  1. The outer () functions stack frame is available in the nested function
  2. Jump and execute code from the nested function.
Some other notes:
  • Nested functions are not a part of ANSI C, however, they are part of Gnu C.
  • The only reason nested functions are possibly useful because they use common stack variables.

Friday, April 30, 2021

Math: Simple technique to implement moving averages in Java, C or C++

 The oneline solution is:

accumulator = (alpha * new_value) + (1.0 - alpha) * accumulator
Here,

Accummulator - holds the value being tracked
alpha - value between 0 and 1.

The more aggressive the alpha (closer to 1) the  faster the moving average adapts to the recent values. This is an exponential moving average.

Wednesday, February 1, 2017

Code snippet to maintain moving averages

I want to maintain moving averages over a window without keeping individual elements in that window. A simple way to do it?

double approxRunningAverage (double avgres, double new_measurement) {

    avgres -= avgres / N;
    avgres += new_measurement / N;

    return avgres;
}