C Polymorphism

Date Tags c

Polymorphism, when done right, is a powerful method of simplifying software implementation. There are multiple types of polymorphism, here is a simple example of runtime (aka dynamic) polymorphism in C:

#include <stdio.h>
#include <stdlib.h>

typedef struct animal_s {
    void (*speak)(void);
} animal_t;

void speak_like_a_duck(void)
{
    printf("quack!\r\n");
}

void speak_like_a_dog(void)
{
    printf("woof!\r\n");
}

animal_t *create_duck(void)
{
    animal_t *duck = malloc(sizeof(animal_t));
    duck->speak = &speak_like_a_duck;
    return(duck);
}

animal_t *create_dog(void)
{
    animal_t *dog …
more ...

C Moving Average

Date Tags c

Moving averages are useful since they do not require a buffer of samples to be maintained. Here is a simple implementation in C:

#include <stdio.h>

float ave(float num)
{
    static float fAve = 0.0f;
    static unsigned int fSmp = 0;
    float weight = 0.0f;

    fSmp++;
    weight = 1.0f / fSmp;
    fAve = (weight * num) + ((1 - weight) * fAve);

    return(fAve);
}

int main(int argc, const char *argv[])
{
    char str[100] = {0};
    float num = 0;

    /* Run until user enters …
more ...

Hi, I am Jeff Rimko!
A computer engineer and software developer in the greater Pittsburgh, Pennsylvania area.