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

前端 未结 23 1440
独厮守ぢ
独厮守ぢ 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:36

    Looking through the answers no one's explicitly stated the sort of practice I make a habit of, telling the story of your code:

    int j = 0;
    for (int i = 0 ; i < 100 ; ++i)
    {
        if (i % 2 == 0)
        {
            j++;
        }
    }
    

    Becomes:

    int j = 0;
    for (int i = 0 ; i < 100 ; ++i)
    {
        if (i % 2 == 0) j++;
    }
    

    Putting the j++ on the same line as the if should signal to anyone else, "I only want this block to ever increment j". Of coursethis is only worthwhile if the line is as simplistic as possible, because putting a breakpoint here, as peri mentions, is not going to be very useful.

    In fact I've just run across part of the Twitter Storm API that has this 'sort' of code in java, here is the relvant snippet form the execute code, on page 43 of this slideshow:

    ...
    Integer Count = counts.get(word);
    if (Count=null) count=0;
    count++
    ...
    

    The for loop block has two things in it, so I wouldn't inline that code. I.e never:

    int j = 0;
    for (int i = 0 ; i < 100 ; ++i) if (i % 2 == 0) j++;
    

    It's awful and I don't even know if it works (as intended); don't do this. New lines and braces help distinguish separate but related pieces of code, in the same way a comma or a semi-colon do in prose. The above block is as bad a really long sentence with a few clauses and some other statements that never break or pause to distinguish separate parts.

    If you really want to telegraph to someone else it's a one-line only job use a ternary operator or ?: form:

    for (int i = 0 ; i < 100 ; ++i) (i%2 ? 0 : >0) j++;
    

    But this is verging on code-golf, and I think not great practice (It's not clear to me if I should put the j++ on one side of the : or not). NB I've not run a ternary operator in C++ before, I don't know if this works, but it does exist.

    In short:

    Imagine how your reader (i.e. the person maintaing the code) interprets your story (code). Make it as clear for them as possible. If you know the novice coder/student is maintaining this, perhaps even leave in as many {} as possible, just so they don't get confused.

提交回复
热议问题