Is there any difference in these two? If so, what exactly is the difference? Assume they are in a C function that may be called multiple times.
-
declare and assign in same statement
static uint32_t value = x;// x varies and may be passed into function. -
declare in one statement and assign in next statment.
static uint32_t value;value = x; // x varies;
Is value updated only the first time it is declared/initialized or even on subsequent calls.
My understanding of (1) is that it is only set the first time that line is executed so even if x changes the next time the line executes, value will remain the same. I am not sure about (2) but clarification on both will be very helpful
EDIT: Compiler ARM(ADS1.20). EDIT: A follow up question on (2) from the answers given so far. Is the declaration(not the assignment) repeated on every call or just the first time?
The first should not compile; the static variable requires a constant initializer.
The second sets
valueeach time the function is called, so there was no need to make itstaticin the first place.If the first notation was correct – initialized
valueto 1, say – then it would be initialized once when the program starts and would thereafter only take new values when the code changed it. The second notation still setsvalueon each call to the function, and so renders the use ofstaticpointless. (Well, if you try hard enough, you can devise scenarios under which the second version has a use for static. For example, if the function returns a pointer to it that other code then modifies, then it might be needed, but that is esoteric in the extreme and would be a pretty bad ‘code smell’.)