Should I initialize variables separately from their declaration?

I am learning C-language. The book says:

"initialize a variable when declaring it only if the initial value is part of the semantics of the variable. If the initial value is part of the algorithm, use a separate assignment operator. For example, instead

int price = units * UNIT_PRICE; int gst = price * GST; 

Record

 int price, gst; price = units * UNIT_PRICE; gst = price * GST; 

I do not understand why we should do this? What are the reasons for this?

+6
c coding-style
source share
4 answers

This is really a programming issue. The author probably says that separating the declaration from its usual purpose makes the code more understandable and understandable at first glance. If, on the other hand, the initial assignment is part of the value of a variable, then declaration and definition can be combined. An example of this would be an int with a boolean value, for example int AnExceptionHasOccurred = FALSE .

+6
source share

As long as you fully set the value before using it, no matter how you do it. This is usually a good style to first set a reasonable default or sentinel if it can change later.

This is because you have no guarantee that an uninitialized variable can have a value if it is specified before setting it, and this is a style error.

+2
source share

I always prefer variable initialization.

My first preference is to write exactly what the OP suggested, i.e.

 int price = units * UNIT_PRICE; int gst = price * GST; 

If this 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 goal is to always keep the variables in a "known" state.

I don't like to write

 int price, gst; 

because at the end of the above statement, the price and gst have โ€œunknownโ€ or โ€œrandomโ€ values.

+2
source share

Perhaps the author claims that in the code below the initialization is semantically based on the input to the algorithm - in the case below unity , this is the input for some algorithm. Initializing to 0 or something does not make sense than just letting garbage that is already in use in memory - both are invalid for an algorithm that matters to the author will argue.

  price = units * UNIT_PRICE; gst = price * GST; 
+1
source share

All Articles