What's the purpose of using braces (i.e. {}) for a single-line if or loop?

前端 未结 23 1446
独厮守ぢ
独厮守ぢ 2020-11-28 00:33

I\'m reading some lecture notes of my C++ lecturer and he wrote the following:

  1. Use Indentation // OK
  2. Never rely on operator preced
23条回答
  •  我在风中等你
    2020-11-28 01:26

    Because when you have two statements without {}, it's easy to miss an issue. Let's assume that the code looks like this.

    int error = 0;
    enum hash_type hash = SHA256;
    struct hash_value *hash_result = hash_allocate();
    
    if ((err = prepare_hash(hash, &hash_result))) != 0)
        goto fail;
    if ((err = hash_update(&hash_result, &client_random)) != 0)
        goto fail;
    if ((err = hash_update(&hash_result, &server_random)) != 0)
        goto fail;
    if ((err = hash_update(&hash_result, &exchange_params)) != 0)
        goto fail;
        goto fail;
    if ((err = hash_finish(hash)) != 0)
        goto fail;
    
    error = do_important_stuff_with(hash);
    
    fail:
    hash_free(hash);
    return error;
    

    It looks fine. The issue with it is really easy to miss, especially when the function containing the code is way larger. The issue is that goto fail is ran unconditionally. You can easily imagine how frustrating this is (making you ask why last hash_update always fails, after all everything looks fine in hash_update function).

    However, that doesn't mean I'm for adding {} everywhere (in my opinion, seeing {} everywhere is annoying). While it can cause issues, it never did for my own projects, as my personal coding style forbids conditionals without {} when they aren't on the same line (yes, I agree that my coding style is unconventional, but I like it, and I use project's code style when contributing to other projects). This makes the following code fine.

    if (something) goto fail;
    

    But not the following one.

    if (something)
        goto fail;
    

提交回复
热议问题