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.7k 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.
  • T Offline
    T Offline
    tomy
    wrote on 14 Oct 2017, 17:20 last edited by tomy
    #1

    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.

    J 1 Reply Last reply 14 Oct 2017, 17:45
    0
    • T tomy
      14 Oct 2017, 17:20

      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.

      J Offline
      J Offline
      JonB
      wrote on 14 Oct 2017, 17:45 last edited by JonB
      #2

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

      T 1 Reply Last reply 15 Oct 2017, 22:02
      4
      • C Offline
        C Offline
        Chris Kawa
        Lifetime Qt Champion
        wrote on 14 Oct 2017, 17:49 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.

        J 1 Reply Last reply 14 Oct 2017, 19:28
        1
        • ? Offline
          ? Offline
          A Former User
          wrote on 14 Oct 2017, 17:56 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;
          
          J 1 Reply Last reply 14 Oct 2017, 18:00
          0
          • ? A Former User
            14 Oct 2017, 17:56

            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;
            
            J Offline
            J Offline
            JonB
            wrote on 14 Oct 2017, 18:00 last edited by
            #5

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

            ? 1 Reply Last reply 14 Oct 2017, 18:02
            0
            • J JonB
              14 Oct 2017, 18:00

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

              ? Offline
              ? Offline
              A Former User
              wrote on 14 Oct 2017, 18:02 last edited by
              #6

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

              J 1 Reply Last reply 14 Oct 2017, 18:05
              0
              • ? A Former User
                14 Oct 2017, 18:02

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

                J Offline
                J Offline
                JonB
                wrote on 14 Oct 2017, 18:05 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 14 Oct 2017, 18:08
                0
                • J JonB
                  14 Oct 2017, 18:05

                  @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 14 Oct 2017, 18:08 last edited by
                  #8

                  @JNBarchan Yep, total desaster.

                  1 Reply Last reply
                  0
                  • SGaistS Offline
                    SGaistS Offline
                    SGaist
                    Lifetime Qt Champion
                    wrote on 14 Oct 2017, 19:25 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
                    • C Chris Kawa
                      14 Oct 2017, 17:49

                      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.

                      J Offline
                      J Offline
                      JonB
                      wrote on 14 Oct 2017, 19:28 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 :)

                      C 1 Reply Last reply 14 Oct 2017, 19:43
                      0
                      • J JonB
                        14 Oct 2017, 19:28

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

                        C Offline
                        C Offline
                        Chris Kawa
                        Lifetime Qt Champion
                        wrote on 14 Oct 2017, 19:43 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? ;)

                        J 1 Reply Last reply 14 Oct 2017, 19:53
                        2
                        • C Chris Kawa
                          14 Oct 2017, 19:43

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

                          J Offline
                          J Offline
                          JonB
                          wrote on 14 Oct 2017, 19:53 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{ }.

                          C 1 Reply Last reply 14 Oct 2017, 20:02
                          0
                          • J JonB
                            14 Oct 2017, 19:53

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

                            C Offline
                            C Offline
                            Chris Kawa
                            Lifetime Qt Champion
                            wrote on 14 Oct 2017, 20:02 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
                            • J JonB
                              14 Oct 2017, 17:45

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

                              T Offline
                              T Offline
                              tomy
                              wrote on 15 Oct 2017, 22:02 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 16 Oct 2017, 22:32
                              0
                              • T tomy
                                15 Oct 2017, 22:02

                                @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 16 Oct 2017, 22:32 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

                                T 1 Reply Last reply 17 Oct 2017, 10:48
                                2
                                • kshegunovK kshegunov
                                  16 Oct 2017, 22:32

                                  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.

                                  T Offline
                                  T Offline
                                  tomy
                                  wrote on 17 Oct 2017, 10:48 last edited by
                                  #16

                                  @kshegunov
                                  Thank you very much for your explanations.

                                  1 Reply Last reply
                                  0
                                  • VRoninV Offline
                                    VRoninV Offline
                                    VRonin
                                    wrote on 17 Oct 2017, 17:55 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

                                    1/17

                                    14 Oct 2017, 17:20

                                    • Login

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