Our website uses cookies to enhance your browsing experience.
Accept
to the top
close form

Fill out the form in 2 simple steps below:

Your contact information:

Step 1
Congratulations! This is your promo code!

Desired license type:

Step 2
Team license
Enterprise license
** By clicking this button you agree to our Privacy Policy statement
close form
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
* By clicking this button you agree to our Privacy Policy statement

close form
Free PVS‑Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

close form
To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

close form
I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

close form
check circle
Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
Uninitialized variable

Uninitialized variable

Mar 12 2013

An uninitialized variable is a variable that is declared but is not set to a definite known value before it is used.

Use of uninitialized variables is similar to use of uninitialized memory and might be a source of errors of different kinds to occur during program execution.

Consider the following example:

int Sum(int n)
{
  int sum, i;
 
  for (i = 0; i < n; i++)
  {
    sum = sum + 1;
  }
 
  return sum;
}

The 'sum' variable wasn't assigned an initial value, and now it contains some "garbage". In some cases, if you're lucky enough, it may also be set to zero enabling the function to work correctly. But in general the function return result is unpredictable. What is tricky about these errors is that the program may work correctly for a long time. One day, after you have changed to another compiler or made some refactoring or other changes, the program will start producing wrong results. Moreover, it may behave quite differently every time you run it.

To avoid such errors in the C++ language, it's the best practice to set all variables to initial values as you declare them. And it's best to declare variables immediately before using them, when their initial values are already known. Taking this into account, we can fix our code sample in the following way:

int Sum(int n)
{
  int sum = 0;
 
  for (int i = 0; i < n; i++)
  {
    sum = sum + 1;
  }
 
  return sum;
}

The PVS-Studio analyzer can perform some diagnostics that allow you to detect certain errors related to the use of uninitialized variables. For example: V573, V614.

References

Popular related articles


Comments (0)

Next comments next comments
close comment form