Consider the following function
int16_t read_input(void)
{
static int32_t previous_input = read_encoder(); // <--Not a compile time constant
//Read current_input
if (previous_input - current_input > SOME_THRESHLD)
some_action();
previous_input = current_input;
//some more code + return statement
}
Since the variable is not initialised to a compile time constant I an not able to declare it without errors.There are 2 reasons why I want to keep the variable as static variable inside the function
1) The variable is not getting used anywhere else in the program. So there is no need of keeping it as a global variable
2) The previous function needs to be initialised to current input or else during the initial run the difference between current input and previous input can go very high because of the encoder connected to current input (and there is no way of telling where could be the encoder value which depends on how much the user has rotated it before turning it off). This will create false triggering of other functions.
Is there any way of declaring a static variable inside a function and initializing it to value similar to example given above?
Note : This problem is a part of a complex program and I have simplified it to avoid complexity. If there is any ambiguity in the question please let me know
previous_inputto a value thatread_encodernever returns. For example, ifread_encoderreturns a number between 0 and 1023, then initializingprevious_inputto -1 allows the code to detect that there was no previous input.