Unicorn with delicious cookie
Nous utilisons des cookies pour améliorer votre expérience de navigation. En savoir plus
Accepter
to the top
>
>
>
Uninitialized variable

Uninitialized variable

12 Mar 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

S'abonner

Comments (0)

close comment form
close form

Remplissez le formulaire ci‑dessous en 2 étapes simples :

Vos coordonnées :

Étape 1
Félicitations ! Voici votre code promo !

Type de licence souhaité :

Étape 2
Team license
Enterprise licence
** En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité
close form
Demandez des tarifs
Nouvelle licence
Renouvellement de licence
--Sélectionnez la devise--
USD
EUR
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
La licence PVS‑Studio gratuit pour les spécialistes Microsoft MVP
close form
Pour obtenir la licence de votre projet open source, s’il vous plait rempliez ce formulaire
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
I want to join the test
* En cliquant sur ce bouton, vous déclarez accepter notre politique de confidentialité

close form
check circle
Votre message a été envoyé.

Nous vous répondrons à


Si l'e-mail n'apparaît pas dans votre boîte de réception, recherchez-le dans l'un des dossiers suivants:

  • Promotion
  • Notifications
  • Spam