I have a problem of how to handle registering of a callback function.
In Example 1, I commented away reg_cb(f1); and in the function irq_handler() the check is working ok (callback = NULL).
However in the second example, Example 2 where the callback function is an element in a struct, the handling is a bit strange. If I comment away bp->func = f1; it looks like the check does not realize the element is NULL.
I don't realise what is going on. Can anyone explain this please?
Regards
Example 1
Code:
#include <stdio.h>
#include <stdlib.h>
void f1()
{
printf("%s() -\n", __func__);
}
void (*callback)(void);
void reg_cb(void(*cb)(void))
{
printf("%s() -\n", __func__);
callback = cb;
}
void irq_handler(void)
{
printf("%s() -\n", __func__);
if (callback != NULL)
{
callback();
}
else
{
printf("cb not registered\n");
}
}
int main(int argc, char *argv[])
{
reg_cb(f1);
irq_handler();
return 0;
}
Example 2
Code:
#include <stdio.h>
#include <stdlib.h>
void f1()
{
printf("%s() -\n", __func__);
}
struct block
{
int var;
void (*func)(void);
};
int main(int argc, char *argv[])
{
struct block *bp;
struct block b;
bp = &b;
bp->var = 10;
bp->func = f1;
printf("var=%d\n", bp->var);
if (bp->func)
{
bp->func();
}
else
{
printf("Not registered\n");
}
return 0;
}