Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. Conditional operator as a statement
Forum Updated to NodeBB v4.3 + New Features

Conditional operator as a statement

Scheduled Pinned Locked Moved Unsolved C++ Gurus
48 Posts 9 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.
  • jsulmJ jsulm

    @JonB said in Conditional operator as a statement:

    (x ? y : z) = 42;

    Should remember this next time I ask for code review for a C++ commit :-D

    JonBJ Offline
    JonBJ Offline
    JonB
    wrote on last edited by
    #17

    @jsulm
    Indeed :) I took this from https://en.cppreference.com/w/cpp/language/operator_other.html, at the end of the Conditional operator sub-topic, where they give:

        // simple lvalue example
        int m = 10; 
        (n == m ? n : m) = 7; // n == m is false, so m = 7
    

    ! :)

    1 Reply Last reply
    0
    • JonBJ JonB

      @SimonSchroeder said in Conditional operator as a statement:

      The general rule is to never user ?:, but to use regular if/else instead.

      Hi Simon. I always read your posts with interest. To be 100% clear, you are not speaking about using ? : in general in its normal "expression-result" context are you? You have no problem with e.g. variable = b ? x() : y();, do you? Only with using it as a statement, b ? x() : y();, right? Where we are indeed all agreeing this is not a "recommended" construct.

      Reading through the C++ standard now I come across two apparently legitimate uses of ? : which are surprising to me at least, and germane to this thread.

      First, they spend time discussing what to do when either side of the : is of type void. Which I cannot see as usable in any context where the expression result is used (e.g. assignment to variable or in an if condition). This only makes sense (to me) in statement

      cond ? voidFunc() : voidFunc2();
      

      Second, they further comment on the result of the : being potentially an lvalue rather than the typical rvalue one would expect. This only makes sense (to me) in statement

      (x ? y : z) = 42;
      

      which perhaps surprisingly is apparently legitimate.

      J.HilkJ Offline
      J.HilkJ Offline
      J.Hilk
      Moderators
      wrote on last edited by
      #18

      @JonB said in Conditional operator as a statement:

      Second, they further comment on the result of the : being potentially an lvalue rather than the typical rvalue one would expect. This only makes sense (to me) in statement

      (x ? y : z) = 42;
      

      which perhaps surprisingly is apparently legitimate.

      ++++++++++[>++++++++++<-]>+++++.                    T
      >++++++++++[>++++++++++<-]>+++++++++++++++++.       h
      +++++++++.                                          a
      +++++.                                              n
      --------.                                           k
      +++.                                               s
      +++++++++++++.                                      ,
      >++++++++++[>++++++++++<-]>++++++++++++.            (space)
      <++++[>++++++++<-]>.                                I
      >++++++++++[>++++++++++<-]>+.                       (space)
      +++++++++++++++.                                    h
      +.                                                 a
      +++.                                               t
      ---------.                                         e
      >++++++++++[>++++++++++<-]>+.                       (space)
      +++++++++++++++.                                    i
      ----.                                              t
      +.                                                 .
      

      Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


      Q: What's that?
      A: It's blue light.
      Q: What does it do?
      A: It turns blue.

      JonBJ jsulmJ 2 Replies Last reply
      0
      • J.HilkJ J.Hilk

        @JonB said in Conditional operator as a statement:

        Second, they further comment on the result of the : being potentially an lvalue rather than the typical rvalue one would expect. This only makes sense (to me) in statement

        (x ? y : z) = 42;
        

        which perhaps surprisingly is apparently legitimate.

        ++++++++++[>++++++++++<-]>+++++.                    T
        >++++++++++[>++++++++++<-]>+++++++++++++++++.       h
        +++++++++.                                          a
        +++++.                                              n
        --------.                                           k
        +++.                                               s
        +++++++++++++.                                      ,
        >++++++++++[>++++++++++<-]>++++++++++++.            (space)
        <++++[>++++++++<-]>.                                I
        >++++++++++[>++++++++++<-]>+.                       (space)
        +++++++++++++++.                                    h
        +.                                                 a
        +++.                                               t
        ---------.                                         e
        >++++++++++[>++++++++++<-]>+.                       (space)
        +++++++++++++++.                                    i
        ----.                                              t
        +.                                                 .
        
        JonBJ Offline
        JonBJ Offline
        JonB
        wrote on last edited by
        #19

        @J.Hilk
        I recognise the code language in your blob! It is "brainf*ck", and I have previously done a bit of coding/playing in it! :) One of the finest, simple languages out there, I don't know why it is not used widely in real world programming ;-)

        J.HilkJ JonBJ 2 Replies Last reply
        0
        • JonBJ JonB

          @J.Hilk
          I recognise the code language in your blob! It is "brainf*ck", and I have previously done a bit of coding/playing in it! :) One of the finest, simple languages out there, I don't know why it is not used widely in real world programming ;-)

          J.HilkJ Offline
          J.HilkJ Offline
          J.Hilk
          Moderators
          wrote on last edited by
          #20

          @JonB turing completeness is all you need.

          Everything else is for those nerds that are concerned with silly stuff like compute time or physical limits of memory.

          Pfft


          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


          Q: What's that?
          A: It's blue light.
          Q: What does it do?
          A: It turns blue.

          JonBJ 1 Reply Last reply
          0
          • J.HilkJ J.Hilk

            @JonB turing completeness is all you need.

            Everything else is for those nerds that are concerned with silly stuff like compute time or physical limits of memory.

            Pfft

            JonBJ Offline
            JonBJ Offline
            JonB
            wrote on last edited by
            #21

            @J.Hilk
            It's great. Simple, clearly documented, and no undefined behaviour. As a bonus IIRC (unless I am mistaken, haven't checked?) you cannot actually put comments into your code (unless yours work because it ignores any non-language characters?), which is also great for code writing....

            J.HilkJ 1 Reply Last reply
            0
            • JonBJ JonB

              @J.Hilk
              It's great. Simple, clearly documented, and no undefined behaviour. As a bonus IIRC (unless I am mistaken, haven't checked?) you cannot actually put comments into your code (unless yours work because it ignores any non-language characters?), which is also great for code writing....

              J.HilkJ Offline
              J.HilkJ Offline
              J.Hilk
              Moderators
              wrote on last edited by J.Hilk
              #22

              @JonB No question about it.

              But the perfect programming language is GulfOfMexico (previously known as DreamBerd)

              I highly recommend checking it out:

              https://github.com/TodePond/GulfOfMexico


              Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


              Q: What's that?
              A: It's blue light.
              Q: What does it do?
              A: It turns blue.

              1 Reply Last reply
              0
              • J.HilkJ J.Hilk

                @JonB said in Conditional operator as a statement:

                Second, they further comment on the result of the : being potentially an lvalue rather than the typical rvalue one would expect. This only makes sense (to me) in statement

                (x ? y : z) = 42;
                

                which perhaps surprisingly is apparently legitimate.

                ++++++++++[>++++++++++<-]>+++++.                    T
                >++++++++++[>++++++++++<-]>+++++++++++++++++.       h
                +++++++++.                                          a
                +++++.                                              n
                --------.                                           k
                +++.                                               s
                +++++++++++++.                                      ,
                >++++++++++[>++++++++++<-]>++++++++++++.            (space)
                <++++[>++++++++<-]>.                                I
                >++++++++++[>++++++++++<-]>+.                       (space)
                +++++++++++++++.                                    h
                +.                                                 a
                +++.                                               t
                ---------.                                         e
                >++++++++++[>++++++++++<-]>+.                       (space)
                +++++++++++++++.                                    i
                ----.                                              t
                +.                                                 .
                
                jsulmJ Offline
                jsulmJ Offline
                jsulm
                Lifetime Qt Champion
                wrote on last edited by
                #23

                @J.Hilk Brainfuck?

                https://forum.qt.io/topic/113070/qt-code-of-conduct

                1 Reply Last reply
                1
                • JonBJ JonB

                  @J.Hilk
                  I recognise the code language in your blob! It is "brainf*ck", and I have previously done a bit of coding/playing in it! :) One of the finest, simple languages out there, I don't know why it is not used widely in real world programming ;-)

                  JonBJ Offline
                  JonBJ Offline
                  JonB
                  wrote on last edited by
                  #24

                  @jsulm

                  @JonB said in Conditional operator as a statement:

                  @J.Hilk
                  I recognise the code language in your blob! It is "brainf*ck",

                  But I was a bit politer than you in what I typed to leave on a forum.

                  1 Reply Last reply
                  0
                  • GrecKoG GrecKo

                    If there's a doubt there's no doubt.

                    That's a weird line of code that makes you double check it to be sure you understood correctly, thus it should be avoided.

                    Kent-DorfmanK Offline
                    Kent-DorfmanK Offline
                    Kent-Dorfman
                    wrote on last edited by Kent-Dorfman
                    #25

                    @Christian-Ehrlicher said in Conditional operator as a statement:

                    btw: I've a similar statement in python where I sa a c++ programmer always have to thunk about it: a = 3 if b == 4 else 5

                    Actually I use that python ternary-if statement quite frequently, but as for using a ternary-if as a statement in c++: I would NOT do it in my code as a statement, but only as an evaluated expression, usually assigning the result.

                    I'm a huge fan of ternary-if, btw! I find myself preferring it in yes/no situations..

                    If you meet the AI on the road, kill it.

                    JonBJ 1 Reply Last reply
                    0
                    • Kent-DorfmanK Kent-Dorfman

                      @Christian-Ehrlicher said in Conditional operator as a statement:

                      btw: I've a similar statement in python where I sa a c++ programmer always have to thunk about it: a = 3 if b == 4 else 5

                      Actually I use that python ternary-if statement quite frequently, but as for using a ternary-if as a statement in c++: I would NOT do it in my code as a statement, but only as an evaluated expression, usually assigning the result.

                      I'm a huge fan of ternary-if, btw! I find myself preferring it in yes/no situations..

                      JonBJ Offline
                      JonBJ Offline
                      JonB
                      wrote on last edited by
                      #26

                      @Kent-Dorfman said in Conditional operator as a statement:

                      python ternary-if statement

                      It cannot be used as a statement in Python, only as an expression. That's what we are talking about compared to C++'s ? :.

                      1 Reply Last reply
                      0
                      • JonBJ JonB

                        @SimonSchroeder said in Conditional operator as a statement:

                        The general rule is to never user ?:, but to use regular if/else instead.

                        Hi Simon. I always read your posts with interest. To be 100% clear, you are not speaking about using ? : in general in its normal "expression-result" context are you? You have no problem with e.g. variable = b ? x() : y();, do you? Only with using it as a statement, b ? x() : y();, right? Where we are indeed all agreeing this is not a "recommended" construct.

                        Reading through the C++ standard now I come across two apparently legitimate uses of ? : which are surprising to me at least, and germane to this thread.

                        First, they spend time discussing what to do when either side of the : is of type void. Which I cannot see as usable in any context where the expression result is used (e.g. assignment to variable or in an if condition). This only makes sense (to me) in statement

                        cond ? voidFunc() : voidFunc2();
                        

                        Second, they further comment on the result of the : being potentially an lvalue rather than the typical rvalue one would expect. This only makes sense (to me) in statement

                        (x ? y : z) = 42;
                        

                        which perhaps surprisingly is apparently legitimate.

                        S Offline
                        S Offline
                        SimonSchroeder
                        wrote on last edited by
                        #27

                        @JonB said in Conditional operator as a statement:

                        You have no problem with e.g. variable = b ? x() : y();, do you? Only with using it as a statement, b ? x() : y();, right?

                        You are correct, I don't have a problem with variable assignment. (I tried to clarify this by the examples I gave.) Still, I would say the general rule is to not use them. You should only use them when you really need them. Sometimes there is no other language feature that could achieve the same thing, and then it is totally fine. Just don't be too smart about it.

                        (I'm personally a heavy user of ?:. I have just accidentially found this 'beauty' in my source:

                        std::ifstream in_winter(type == MIN ? "stats-" + std::to_string(year) + "-winter-min.csv"
                                              : type == MAX ? "stats-" + std::to_string(year) + "-winter-max.csv"
                                                            : "stats-" + std::to_string(year) + "-winter-mean.csv");
                        

                        MIN and MAX are enum values.)

                        J.HilkJ JonBJ 2 Replies Last reply
                        0
                        • S SimonSchroeder

                          @JonB said in Conditional operator as a statement:

                          You have no problem with e.g. variable = b ? x() : y();, do you? Only with using it as a statement, b ? x() : y();, right?

                          You are correct, I don't have a problem with variable assignment. (I tried to clarify this by the examples I gave.) Still, I would say the general rule is to not use them. You should only use them when you really need them. Sometimes there is no other language feature that could achieve the same thing, and then it is totally fine. Just don't be too smart about it.

                          (I'm personally a heavy user of ?:. I have just accidentially found this 'beauty' in my source:

                          std::ifstream in_winter(type == MIN ? "stats-" + std::to_string(year) + "-winter-min.csv"
                                                : type == MAX ? "stats-" + std::to_string(year) + "-winter-max.csv"
                                                              : "stats-" + std::to_string(year) + "-winter-mean.csv");
                          

                          MIN and MAX are enum values.)

                          J.HilkJ Offline
                          J.HilkJ Offline
                          J.Hilk
                          Moderators
                          wrote on last edited by
                          #28

                          @SimonSchroeder said in Conditional operator as a statement:

                          (I'm personally a heavy user of ?:. I have just accidentially found this 'beauty' in my source:

                          std::ifstream in_winter(type == MIN ? "stats-" + std::to_string(year) + "-winter-min.csv"
                          : type == MAX ? "stats-" + std::to_string(year) + "-winter-max.csv"
                          : "stats-" + std::to_string(year) + "-winter-mean.csv");
                          MIN and MAX are enum values.)

                          alt text


                          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                          Q: What's that?
                          A: It's blue light.
                          Q: What does it do?
                          A: It turns blue.

                          1 Reply Last reply
                          1
                          • S SimonSchroeder

                            @JonB said in Conditional operator as a statement:

                            You have no problem with e.g. variable = b ? x() : y();, do you? Only with using it as a statement, b ? x() : y();, right?

                            You are correct, I don't have a problem with variable assignment. (I tried to clarify this by the examples I gave.) Still, I would say the general rule is to not use them. You should only use them when you really need them. Sometimes there is no other language feature that could achieve the same thing, and then it is totally fine. Just don't be too smart about it.

                            (I'm personally a heavy user of ?:. I have just accidentially found this 'beauty' in my source:

                            std::ifstream in_winter(type == MIN ? "stats-" + std::to_string(year) + "-winter-min.csv"
                                                  : type == MAX ? "stats-" + std::to_string(year) + "-winter-max.csv"
                                                                : "stats-" + std::to_string(year) + "-winter-mean.csv");
                            

                            MIN and MAX are enum values.)

                            JonBJ Offline
                            JonBJ Offline
                            JonB
                            wrote on last edited by
                            #29

                            @SimonSchroeder

                            std::ifstream in_winter(type == MIN ? "stats-" + std::to_string(year) + "-winter-min.csv"
                                                  : type == MAX ? "stats-" + std::to_string(year) + "-winter-max.csv"
                                                                : "stats-" + std::to_string(year) + "-winter-mean.csv");
                            

                            I think it's fine you chose ? : here. if else would have been much longer. But just for the record I have a thing about about factoring and not repeating. I would probably have written yours as something like:

                            var amount = (type == MIN) ? "min" : (type == MAX) ? "max" : "mean";
                            std::ifstream in_winter("stats-" + std::to_string(year) + "-winter-" + amount + ".csv");
                            

                            :) To me this makes it clear that the "test" is simply for the word min/max/mean and everything else is the same. And the lines are not too long!

                            J.HilkJ 1 Reply Last reply
                            0
                            • JonBJ JonB

                              @SimonSchroeder

                              std::ifstream in_winter(type == MIN ? "stats-" + std::to_string(year) + "-winter-min.csv"
                                                    : type == MAX ? "stats-" + std::to_string(year) + "-winter-max.csv"
                                                                  : "stats-" + std::to_string(year) + "-winter-mean.csv");
                              

                              I think it's fine you chose ? : here. if else would have been much longer. But just for the record I have a thing about about factoring and not repeating. I would probably have written yours as something like:

                              var amount = (type == MIN) ? "min" : (type == MAX) ? "max" : "mean";
                              std::ifstream in_winter("stats-" + std::to_string(year) + "-winter-" + amount + ".csv");
                              

                              :) To me this makes it clear that the "test" is simply for the word min/max/mean and everything else is the same. And the lines are not too long!

                              J.HilkJ Offline
                              J.HilkJ Offline
                              J.Hilk
                              Moderators
                              wrote on last edited by J.Hilk
                              #30

                              @JonB I would have gone with a lambda function and a full switch case approach. We're dealing with enums after all, and it screams at me: "THIS WILL EXPAND TO MORE FILES!"


                              Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                              Q: What's that?
                              A: It's blue light.
                              Q: What does it do?
                              A: It turns blue.

                              JonBJ 1 Reply Last reply
                              0
                              • J.HilkJ J.Hilk

                                @JonB I would have gone with a lambda function and a full switch case approach. We're dealing with enums after all, and it screams at me: "THIS WILL EXPAND TO MORE FILES!"

                                JonBJ Offline
                                JonBJ Offline
                                JonB
                                wrote on last edited by JonB
                                #31

                                @J.Hilk said in Conditional operator as a statement:

                                lambda function and a full switch case approach

                                Nah....!! KISS!! :)

                                And for the record I wouldn't use a switch statement to return a simple value where there are only 2 explicit case and a default. Why write a multiline essay to pick between a couple of literal string values? Of course it's only IMHO, and each to their own....

                                J.HilkJ 1 Reply Last reply
                                0
                                • JonBJ JonB

                                  @J.Hilk said in Conditional operator as a statement:

                                  lambda function and a full switch case approach

                                  Nah....!! KISS!! :)

                                  And for the record I wouldn't use a switch statement to return a simple value where there are only 2 explicit case and a default. Why write a multiline essay to pick between a couple of literal string values? Of course it's only IMHO, and each to their own....

                                  J.HilkJ Offline
                                  J.HilkJ Offline
                                  J.Hilk
                                  Moderators
                                  wrote on last edited by
                                  #32

                                  @JonB I value readability over simplicity for simplicity’s sake..


                                  Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                  Q: What's that?
                                  A: It's blue light.
                                  Q: What does it do?
                                  A: It turns blue.

                                  JonBJ 1 Reply Last reply
                                  0
                                  • J.HilkJ J.Hilk

                                    @JonB I value readability over simplicity for simplicity’s sake..

                                    JonBJ Offline
                                    JonBJ Offline
                                    JonB
                                    wrote on last edited by JonB
                                    #33

                                    @J.Hilk I agree.
                                    And personally I find a couple of ? :s, in one line, as more readable than a multiple line switch statement and a lambda. Each to their own :)

                                    J.HilkJ 1 Reply Last reply
                                    0
                                    • JonBJ JonB

                                      @J.Hilk I agree.
                                      And personally I find a couple of ? :s, in one line, as more readable than a multiple line switch statement and a lambda. Each to their own :)

                                      J.HilkJ Offline
                                      J.HilkJ Offline
                                      J.Hilk
                                      Moderators
                                      wrote on last edited by J.Hilk
                                      #34

                                      @JonB

                                      auto winter_stats_filename = [](int year, Type type) -> std::string {
                                          const char* suffix = "mean"; // Fallback
                                          switch (type) {
                                              case Type::MIN:  suffix = "min";  break;
                                              case Type::MAX:  suffix = "max";  break;
                                              case Type::MEAN: suffix = "mean"; break;
                                              default:
                                                  assert(false && "winter_stats_filename: unexpected Type value");
                                                  break;
                                          }
                                          return "stats-" + std::to_string(year) + "-winter-" + std::string(suffix) + ".csv";
                                      };
                                      
                                      std::ifstream in_winter(winter_stats_filename(year, type));
                                      

                                      I agree, sometimes I have the correct opinion and sometime the others have to wrong opinion :P


                                      Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                      Q: What's that?
                                      A: It's blue light.
                                      Q: What does it do?
                                      A: It turns blue.

                                      JonBJ 1 Reply Last reply
                                      0
                                      • J.HilkJ J.Hilk

                                        @JonB

                                        auto winter_stats_filename = [](int year, Type type) -> std::string {
                                            const char* suffix = "mean"; // Fallback
                                            switch (type) {
                                                case Type::MIN:  suffix = "min";  break;
                                                case Type::MAX:  suffix = "max";  break;
                                                case Type::MEAN: suffix = "mean"; break;
                                                default:
                                                    assert(false && "winter_stats_filename: unexpected Type value");
                                                    break;
                                            }
                                            return "stats-" + std::to_string(year) + "-winter-" + std::string(suffix) + ".csv";
                                        };
                                        
                                        std::ifstream in_winter(winter_stats_filename(year, type));
                                        

                                        I agree, sometimes I have the correct opinion and sometime the others have to wrong opinion :P

                                        JonBJ Offline
                                        JonBJ Offline
                                        JonB
                                        wrote on last edited by JonB
                                        #35

                                        @J.Hilk
                                        To pick whether you want min, max or mean in a string I have to read through 10 lines of your code (and check a lambda for sanity to add to it). Madness! :)

                                        I can grasp

                                        var amount = (type == MIN) ? "min" : (type == MAX) ? "max" : "mean";
                                        

                                        at a single glance.

                                        (Yes, I know you have added enum-range checking in your code which adds a few lines compared to mine.)

                                        J.HilkJ 1 Reply Last reply
                                        0
                                        • JonBJ JonB

                                          @J.Hilk
                                          To pick whether you want min, max or mean in a string I have to read through 10 lines of your code (and check a lambda for sanity to add to it). Madness! :)

                                          I can grasp

                                          var amount = (type == MIN) ? "min" : (type == MAX) ? "max" : "mean";
                                          

                                          at a single glance.

                                          (Yes, I know you have added enum-range checking in your code which adds a few lines compared to mine.)

                                          J.HilkJ Offline
                                          J.HilkJ Offline
                                          J.Hilk
                                          Moderators
                                          wrote on last edited by
                                          #36

                                          @JonB I'm sorry but very time I see chained ternary operators, I get an Undertale rash.


                                          Be aware of the Qt Code of Conduct, when posting : https://forum.qt.io/topic/113070/qt-code-of-conduct


                                          Q: What's that?
                                          A: It's blue light.
                                          Q: What does it do?
                                          A: It turns blue.

                                          JonBJ 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