Sorry if this is a silly question :-)
I have legacy code that looks like this:
struct {
int field1;
int field2;
int field3;
int field4;
... many many fields
} myStruct;
while (something) {
initialzationFunction(&myStruct);
// ...change fields of myStruct and do stuff.
}
Each iteration of the while loop needs that myStruct will be initialized to something, lets say zero. initialzationFunction initializes all the fields of myStruct to zero.
Is it good to keep initialzationFunction inside the while loop, or is it better to call it once before the loop, and let the programmers initialize what they need "by hand" if they happen to change this code.
edit: Unfortunately myStruct is a global variable, so making it an automatic variable isn't an option, unless I want to pass it as a parameter to tons of legacy functions that use it.
What would you do?
The initialization is an expression that initializes the loop — it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. When the expression evaluates to false , the loop terminates.
Initialization code (or boot code) takes the processor from the reset state to a state where the operating system can run. It usually configures the memory controller and processor caches and initializes some devices. In a simple system the operating system might be replaced by a simple scheduler or debug monitor.
A 'for' loop can be written without initialization. A 'for' statement usually goes like: for (initialization; test-condition; update). We can leave out any or all three of them at a time.
Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.
If you are leaving the code for others to maintain, and the code is not a proven hotspot, initialize every time as there will be less bugs introduced by others.
If the code is a proven critical hotspot then initialize once and have the code clean up afterwards.
Premature optimisation is the root of all evil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With