Uninitalized variable

I have heard a lot about initializing variables and have wondered why so much is being said about it as long as the developer is going to use the variable sensibly, but i happened to work on a issue where a uninitialized variable (supposed to hold a proper enum value) was passed on to a function working on the following enum values,

-----------------------------------------------------------------------------------------------------------------
[Code]

enum property
{
NAME = 0,
TELEPHONE,
ADDRESS,
E-MAIL,
FAX,
PAGER
};

void act_on_property(int property_type)
{
switch(property_type)
{
case NAME : ...
case TELEPHONE : ...
case ADDRESS : ...
case E-MAIL : ...
case FAX : ...
case PAGER : ...
default : log ("invalid value");
}
}
-----------------------------------------------------------------------------------------------------------------


The problem was that the variable was a global one, having static storage class.

In one particular code flow, the global variable wasn't set to the proper enum value and was passed directly to this function and the default value of 0 ( uninitialized variables being zero filled ) was handled in the switch-case as a NAME property and this had its own negative impact on the use case and caused a considerable time to debug (sounds simple in this case though).

This experience just signifies the importance of initializing variables and in our case, we introduced a new enum value by the name of INVALID_PROPERTY and used this to initialize the global variable, making sure that any future problem could be caught in the default case of the switch-case with a graceful exit. This also gives a hint of having a value in every enumeration which signifies a invalid value.

No comments: