I am learning C language. In the book, it says:
"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?
Variables can either be initialized in the same statement as the declaration or later in the code.
Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it. Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable.
When you declare a variable, you give it a name (name/age) and a type (String/int): String name; int age; Initializing a variable is when you give it a value.
To declare a variable that has been initialized in another file, the keyword extern is always used. By always initializing variables, instead of assigning values to them before they are first used, the code is made more efficient since no temporary objects are created for the initialization.
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
.
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.
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