Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I initialize variables separately from declaring them?

Tags:

c

coding-style

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?

like image 486
ipkiss Avatar asked Mar 03 '11 00:03

ipkiss


People also ask

Can we initialize a variable before we declare it?

Variables can either be initialized in the same statement as the declaration or later in the code.

Can we declare and initialize a variable together?

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.

What is the difference between declaring and initialising a 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.

Why is it important to always initialize variables when you declare them?

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.


2 Answers

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.

like image 193
ThomasMcLeod Avatar answered Oct 19 '22 23:10

ThomasMcLeod


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.

like image 28
jer Avatar answered Oct 19 '22 23:10

jer