Reputation: 13651
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?
Upvotes: 6
Views: 1174
Reputation: 20383
I always prefer initializing variables.
My first preference is to write exactly what OP has suggested, i.e.
int price = units * UNIT_PRICE;
int gst = price * GST;
In case it is not allowed by the local programming standard, I would do
int price = 0;
int gst = 0;
...
price = units * UNIT_PRICE;
gst = price * GST;
The point is to always keep the variables in a "known" state.
I don't like writing
int price, gst;
because at the end of the above statement, the variables price
and gst
have "unknown" or "random" values.
Upvotes: 2
Reputation: 65599
The author is probably arguing that in the code below the initialization semantically is based on an input to the algorithm -- in the case below units is an input to some algorithm. Initializing to 0 or something is no more meaningful than just letting the garbage thats already in the memory to be used--both are invalid to the algorithm that matters the author would argue.
price = units * UNIT_PRICE;
gst = price * GST;
Upvotes: 1
Reputation: 20236
So long as you absolutely set a value before you use it, it doesn't matter how you do it. It's generally good style to set some reasonable default or sentinel value initially though, if it may change later.
This is because you have no guarantees what an uninitialized variable may have for a value if referenced before set, and it's a style bug.
Upvotes: 2
Reputation: 7769
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
.
Upvotes: 6