> For the complete documentation index, see [llms.txt](https://skkv-itmo.gitbook.io/c-cpp-cookies/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://skkv-itmo.gitbook.io/c-cpp-cookies/best-practices/best-practices/deep-ifs.md).

# 6. Глубокие if

{% file src="/files/yLy9d7eTReIrmJMqwI8N" %}
Весь приведённый далее код оформлен с использованием clang-format
{% endfile %}

{% code overflow="wrap" lineNumbers="true" %}

```c
int main(int argc, char *argv[])
{
    if (fopen(argv[1], "r"))
    {
        int size;
        if (fscanf("%d\n", &size) == 1)
        {
            char *arr = malloc(size);
            if (arr != NULL)
            {
                // etc.
            }
            else
            {
                // memory allocation failed
                return 1;
            }
        }
        else
        {
            // cannot open input file
            return 1;
        }
    }
    else
    {
        // cannot open input file
        return 1;
    }
    return 0;
}
```

{% endcode %}

<details>

<summary>Вариант реорганизации и исправления кода</summary>

Большая вложенность условий, циклов и пр. пагубно влияет на просматривающих код, т.к. всегда требуется держать в голове при каких таких условиях мы попали сюда.

{% code overflow="wrap" lineNumbers="true" %}

```c
int main(int argc, char *argv[])
{
    if (!fopen(argv[1], "r"))
    {
        // cannot open input file
        return 1;
    }
    int size;
    if (fscanf("%d\n", &size) != 1)
    {
        // cannot open input file
        return 1;
    }
    char *arr = malloc(size);
    if (arr == NULL)
    {
        // memory allocation failed
        return 1;
    }
    // etc.
    return 0;
}
```

{% endcode %}

</details>
