samedi 9 novembre 2019

Speed over style in C?

What is more important readability or style?

Example:

Say you create a lot of resources in one method and if some operation fails you have to free the ones which were successfully created. Would you rather do that in a general clean up label which will free any resource or free the created resources after the failed operation?

Style 1:

void foo(void)
{
   void* res1, res2, res3;
   res1 = malloc(1);
   if(res1 == NULL)
     return; //operation failed

   res2 = malloc(1);
   if(res2 == NULL)
   {
       free(res1);
       return;
   }

   res3 = malloc(1);
   if(res3 == NULL)
   {
       free(res1);
       free(res2);
       return;
   }
}

Style 2:

void foo(void)
{
   void* res1 = NULL, *res2 = NULL, *res3 = NULL;
   res1 = malloc(1);
   if(res1 == NULL)
     goto lbl_clean_up; //operation failed

   res2 = malloc(1);
   if(res2 == NULL)
   {
       goto lbl_clean_up;
   }

   res3 = malloc(1);
   if(res3 == NULL)
   {
       goto lbl_clean_up;
   }
lbl_clean_up:
   {
       if(res1 != NULL)
          free(res1);
       if(res2 != NULL)
          free(res2);
       if(res3 != NULL)
          free(res3);
       return;
}

Now should I rather use Style 1 or Style 2 ? Style 2 has more redundant if-statements but looks much more readable in my opinion.

Aucun commentaire:

Enregistrer un commentaire