I am wondering if it is possible in plain C (C99) to have a macro which contains static variables which can be used inside conditional expressions.
I came up with the following (as a function):
char EDGE(unsigned long x)
{
static char up = 0;
static unsigned long v;
if (up && v != x) {
v = x;
return 1;
} else {
v = x;
up = 1;
return 0;
}
}
which is exactly what I want, except that it only works once (one misses the cached value on invoking this function with another variable).
So I thought about macros in C and the fact, that if this would work I got a variable cache for free, without having to manage anything. Is this even possible using plain old C?
Note: I want to have a simple to use edge detection 'function' which might be simply invoked inside an if-statement.
For this, you'll need two macros. The first is used to set up an edge function for a particular variable, while the second is used to call the relevant function.
Output:
In each of these macros,
##is the concatenation operator. This combines two tokens into one.When you use the first macro at file scope as:
This expands into:
Now you have a function that can check for an edge condition for
y.Then when you use the second macro:
This expands to:
Note that for this to work, each variable you set up an EDGE function for has to have a unique name, regardless of scope.
EDIT:
Here's another way to do this that doesn't have scoping issues:
In this case, you call the
SET_EDGEmacro just after the relevant variable is defined. This creates another variable with_lastappended to the name, keeping track of the prior value. The address of this state variable is then passed to theedgefunction when you use theEDGEmecro.