I am learning C. In the book, it says to initialize a variable when declaring it only if the initial value is part of the semantic of the variable. If the initial value is part of an algorithm, use a separate assignment statement. For example, instead of:
int price = units * UNIT_PRICE;
int gst = price * GST;
Write:
int price, gst;
price = units * UNIT_PRICE;
gst = price * GST;
I do not understand why we should do that. What are the reasons behind it?
This is really just a matter of programming style. What the author is probably saying is that separating the declaration from a normal assignment makes the code cleaner and easier to understand at a glance. If, on the otherhand, the initial assignment is part of the meaning of the variable, then it’s ok to combine declaration and definition. An example of this might be an int with a boolean value such as
int AnExceptionHasOccurred = FALSE.