C: Nested Ifs or Gotos

后端 未结 5 2230
温柔的废话
温柔的废话 2021-02-15 03:45

What is the best way to manage resources for a C program. Should I use a nested if structure or should I use goto statements?

I am aware there is a lot

5条回答
  •  野性不改
    2021-02-15 04:16

    If by using goto you can avoid writing complex code, then use goto.

    Your example could also be written like this (no gotos):

    void anotherExample()
    {
        char *string1, *string2, *string3, *string4, *string5;
        string1 = string2 = string3 = string4 = string5 = 0;
        if ((string1 = (char*) calloc(STRING_MAX, sizeof(char)))
         && (string2 = (char*) calloc(STRING_MAX, sizeof(char)))
         && (string3 = (char*) calloc(STRING_MAX, sizeof(char)))
         && (string4 = (char*) calloc(STRING_MAX, sizeof(char)))
         && (string5 = (char*) calloc(STRING_MAX, sizeof(char))))
        {
           //important code here
        }
    
      free(string1);
      free(string2);
      free(string3);
      free(string4);
      free(string5);
    }
    

提交回复
热议问题