Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. The rule of braces in Qt programming
Forum Updated to NodeBB v4.3 + New Features

The rule of braces in Qt programming

Scheduled Pinned Locked Moved Unsolved General and Desktop
17 Posts 7 Posters 4.9k Views 5 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Chris KawaC Offline
    Chris KawaC Offline
    Chris Kawa
    Lifetime Qt Champion
    wrote on last edited by Chris Kawa
    #3

    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.

    JonBJ 1 Reply Last reply
    1
    • ? Offline
      ? Offline
      A Former User
      wrote on last edited by
      #4

      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;
      
      JonBJ 1 Reply Last reply
      0
      • ? A Former User

        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;
        
        JonBJ Online
        JonBJ Online
        JonB
        wrote on last edited by
        #5

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

        ? 1 Reply Last reply
        0
        • JonBJ JonB

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

          ? Offline
          ? Offline
          A Former User
          wrote on last edited by
          #6

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

          JonBJ 1 Reply Last reply
          0
          • ? A Former User

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

            JonBJ Online
            JonBJ Online
            JonB
            wrote on last edited by
            #7

            @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.

            ? 1 Reply Last reply
            0
            • JonBJ JonB

              @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.

              ? Offline
              ? Offline
              A Former User
              wrote on last edited by
              #8

              @JNBarchan Yep, total desaster.

              1 Reply Last reply
              0
              • SGaistS Offline
                SGaistS Offline
                SGaist
                Lifetime Qt Champion
                wrote on last edited by SGaist
                #9

                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.

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                1 Reply Last reply
                0
                • Chris KawaC Chris Kawa

                  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.

                  JonBJ Online
                  JonBJ Online
                  JonB
                  wrote on last edited by JonB
                  #10

                  @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 :)

                  Chris KawaC 1 Reply Last reply
                  0
                  • JonBJ JonB

                    @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 :)

                    Chris KawaC Offline
                    Chris KawaC Offline
                    Chris Kawa
                    Lifetime Qt Champion
                    wrote on last edited by Chris Kawa
                    #11

                    @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? ;)

                    JonBJ 1 Reply Last reply
                    2
                    • Chris KawaC Chris Kawa

                      @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? ;)

                      JonBJ Online
                      JonBJ Online
                      JonB
                      wrote on last edited by
                      #12

                      @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{ }.

                      Chris KawaC 1 Reply Last reply
                      0
                      • JonBJ JonB

                        @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{ }.

                        Chris KawaC Offline
                        Chris KawaC Offline
                        Chris Kawa
                        Lifetime Qt Champion
                        wrote on last edited by
                        #13

                        @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 ;)

                        1 Reply Last reply
                        0
                        • JonBJ JonB

                          @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().

                          tomyT Offline
                          tomyT Offline
                          tomy
                          wrote on last edited by
                          #14

                          @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.

                          kshegunovK 1 Reply Last reply
                          0
                          • tomyT tomy

                            @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.

                            kshegunovK Offline
                            kshegunovK Offline
                            kshegunov
                            Moderators
                            wrote on last edited by
                            #15

                            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.

                            Read and abide by the Qt Code of Conduct

                            tomyT 1 Reply Last reply
                            2
                            • kshegunovK kshegunov

                              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.

                              tomyT Offline
                              tomyT Offline
                              tomy
                              wrote on last edited by
                              #16

                              @kshegunov
                              Thank you very much for your explanations.

                              1 Reply Last reply
                              0
                              • VRoninV Offline
                                VRoninV Offline
                                VRonin
                                wrote on last edited by
                                #17

                                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

                                "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                ~Napoleon Bonaparte

                                On a crusade to banish setIndexWidget() from the holy land of Qt

                                1 Reply Last reply
                                1

                                • Login

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • Users
                                • Groups
                                • Search
                                • Get Qt Extensions
                                • Unsolved