The rule of braces in Qt programming



  • Hi,

    I presumably should have said "C++ programming" rather than "Qt programming" but anyway:

    if(event->buttons() & Qt::LeftButton)
            setImagePixel(event->pos(), true);
        else if(event->buttons() & Qt::RightButton);
            setImagePixel(event->pos(), false);
    

    Here, according what I've learnt from C++ nor if neither else if needs braces but the book I read has put braces for either. The Qt creator IDE also suggest using it. Do you agree that they are needless in this case? (because we have only one statement after each)

    By the way, what does that sole reference/address operator '&' mean there please? I've not seen it be used that way yet.



  • @tomy
    In the example you give the braces may be omitted.

    Some people prefer always putting them in for clarity (especially in tutorial books), and to prevent inadvertent errors where it does matter.

    else attaches to nearest if if no braces are used. If the case of if-if-else, without any braces C always treats it as

    if (...)
        if (...)
        else
    

    You have to use braces if you mean:

    if (...)
    {
        if (...)
    }
    else
    

    There is no "reference/address operator '&'" in the code --- those two are both bit-wise ands. They test whether the respective button-bit is set in the int returned by event->buttons().


  • Moderators

    In the particular case of one line statements it doesn't matter to the compiler if the braces are there, but humans make mistakes so it's quite a reasonable policy to always use braces, even when there's just one line.
    Your code got badly formatted indents when you pasted it on the forum and that is a great example why that policy is a good idea. Consider this example:

    if (a)
       doSomething();
       else if (b)
           doSomethingElse();
    

    Now someone takes this code over after you and adds another else to it:

    if (a)
       doSomething();
       else if (b)
           doSomethingElse();
    else
       doYetAnotherThing();
    

    At first glance, because of the formatting you could think that this new else refers to the first if but that's not the case. Adding braces makes it clearer what's going on:

    if (a)
    {
       doSomething();
    }
    else
    {
       if (b)
       {
           doSomethingElse();
       }
       else
       {
          doYetAnotherThing();
       }
    }
    

    People will argue about the increased amount of lines and should you put the opening brace on the same or on the next line, but those are details. The point is that adding these braces saves you from silly formatting mistakes.

    & is not only an address operator. It's also a binary AND. See my older post on these operators and how they are used to handle flags.


  • Moderators

    Without the braces things like the following are a bit more likely to happen:

    if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
            goto fail;
        if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
            goto fail;
        if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
            goto fail;
        if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
            goto fail;
            goto fail;
        if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
            goto fail;
    


  • @Wieland
    Though not in Python... which doesn't use braces... ;-)


  • Moderators

    @JNBarchan Maybe Apple should switch to Python then ;-)



  • @Wieland
    It's OK, I don't much like Python, I prefer C's braces etc. :)

    I think one of the ugliest is, for the elegant:
    a = b ? c : d;
    I have to use:
    a = c if b else d
    Put that in your pipe and smoke it! Ridiculous.


  • Moderators

    @JNBarchan Yep, total desaster.


  • Lifetime Qt Champion

    Hi,

    To add to my fellow developers: there's no "Qt programming". Qt is not a language, it's a C++ framework where the exact same rules applies as any other C++ library/framework.



  • @Chris-Kawa

    To compiler it doesn't matter if the braces are there

    Please be careful about saying this, especially to a learner. In your example and that given by the OP they don't matter, but in other cases (like if-if-else) they most certainly do matter vitally to the compiler! K&R did not put braces into language to make it easier for people to read code :)


  • Moderators

    @JNBarchan Right, I made it more explicit. Thanks.
    As a redeeming bonus here's another reason to always use braces: macros!
    Consider this example:

    #define FOOBAR(x) doSomething(x); \
                      doSomethingElse(x)
    
    if(something)
        FOOBAR(42);
    

    It actually expands to:

    if (something)
       doSomething(42);
    doSomethingElse(42);
    

    Not what we wanted at all. Braces would fix that.

    K&R did not put braces into language to make it easier for people to read code :)

    Is that a fact or you're guessing? ;)



  • @Chris-Kawa

    Is that a fact or you're guessing? ;)

    Guessing ;) But I'm quite sure it's true! Even if they (Ritchie, I believe) thought braces might be nice for people to read, they had to be there semantically for if-if-else regardless of anything else. You can't do that without some kind of statement grouper. Remember that plenty of other languages use exactly the same principle (e.g. Pascal begin-end), there's nothing unique to C here other than the (inspired!) choice of selecting{ }.


  • Moderators

    @JNBarchan Except there are languages that get by with just indenting like Python or F#, so I'd argue that the braces (or Pascalian begin/end) are there mostly for human consumption. The parser would be a lot happier with less braces and more goto jumps.
    Ok, lets not steal the thread for academic disputes. I feel we're on the same page anyway ;)



  • @JNBarchan

    There is no "reference/address operator '&'" in the code --- those two are both bit-wise ands. They test whether the respective button-bit is set in the int returned by event->buttons().

    @Chris-Kawa : I've written numerous C++ apps and have never used braces for one statement except for situations like out of scope of an object calling its destructor. But the code is a simple "if" and "else if" pair.

    @Wieland: In your code, we have at least one goto fail; execution.
    @SGaist: Please read the first line of my first post here.

    Thanks to all.

    Thanks.


  • Qt Champions 2016

    There is no "reference/address operator '&'" in the code --- those two are both bit-wise ands.

    I'll chime in even if a bit late. C++ has a pretty terrible syntax in a sense, because there's a lot of context-dependent meaning of tokens (operators, braces and such). While this is not a problem semantically (pertaining to the meaning), it may be quite a lot for the learners when they try to acquire command of the language. Think about the asterisk * can you name at least three distinct meanings for it? Same goes for the different type of parentheses, brackets and braces - one should be able to name at least two meanings of the brackets, at least two meanings for -> and variants thereof off the top of one's head. There's even the pointer to member dereference operator ->* and three distinct meanings of the &.

    My point here is that this "suggests" it's a very good idea to adopt a strict (code) style if all those nuances are not to lead to errors/confusion.

    As for the braces I personally don't put them around single statements (unless there's a nested if/else/for etc.), however I impose on my code to be always perfectly indented. This means the matching else is to be always at the same column as the corresponding if and so on. Also braces have one more "peculiar" meaning - opening of a block, which allows for shadowing of variable names that is not otherwise possible.



  • @kshegunov
    Thank you very much for your explanations.



  • I think, at the end of the day, this is a style question. Qt has a guideline: https://wiki.qt.io/Qt_Coding_Style , Google has one: https://google.github.io/styleguide/cppguide.html , basically every company has a different one


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.