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
40 Posts 9 Posters 713 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.
  • J.HilkJ Offline
    J.HilkJ Offline
    J.Hilk
    Moderators
    wrote last edited by
    #5

    it's fine, you don't necessarily need to have the same return type either.

    int i = 1;
    double d = 2.5;
    auto x = cond ? i : d;        // -> double 
    

    is totally legit. But it may produce compiler warnings, if the appropriate compiler flag are enabled (-Wconversion, -Wsign-conversion, -Wfloat-conversion etc) and its applicable


    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

      it's fine, you don't necessarily need to have the same return type either.

      int i = 1;
      double d = 2.5;
      auto x = cond ? i : d;        // -> double 
      

      is totally legit. But it may produce compiler warnings, if the appropriate compiler flag are enabled (-Wconversion, -Wsign-conversion, -Wfloat-conversion etc) and its applicable

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote last edited by JonB
      #6

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

      is totally legit.

      Only because int is "promotable" to double. They do not have to the same return type but they at least have to have promotable/convertible return types.

      The (academic) question is whether that is enforced by the ? : operator itself or whether it is only enforced on (say) assignment of the result to a variable or usage in a condition. The situation we are discussing is the (peculiar):

      a ? b() : c();
      

      as a statement, so the result is never used. I still imagine it's the : operator which demands the type compatibility even if the result is not used.

      BTW (I just discovered) the "Standard" says something along these lines:

      5.17/3

      If the second and third operand have different types, and either has (possibly cv-qualified) class type, an attempt is made to convert each of those operands to the type of the other. The process for determining whether an operand expression E1 of type T1 can be converted to match an operand expression E2 of type T2 is defined as follows:

      and then, of course, loads of cases.....

      jeremy_kJ 1 Reply Last reply
      1
      • JonBJ JonB

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

        is totally legit.

        Only because int is "promotable" to double. They do not have to the same return type but they at least have to have promotable/convertible return types.

        The (academic) question is whether that is enforced by the ? : operator itself or whether it is only enforced on (say) assignment of the result to a variable or usage in a condition. The situation we are discussing is the (peculiar):

        a ? b() : c();
        

        as a statement, so the result is never used. I still imagine it's the : operator which demands the type compatibility even if the result is not used.

        BTW (I just discovered) the "Standard" says something along these lines:

        5.17/3

        If the second and third operand have different types, and either has (possibly cv-qualified) class type, an attempt is made to convert each of those operands to the type of the other. The process for determining whether an operand expression E1 of type T1 can be converted to match an operand expression E2 of type T2 is defined as follows:

        and then, of course, loads of cases.....

        jeremy_kJ Offline
        jeremy_kJ Offline
        jeremy_k
        wrote last edited by
        #7

        @JonB I was going to suggest including a link to the relevant standard section, but attempting to do so myself isn't producing satisfactory results.

        https://github.com/cplusplus/draft/blob/main/source/expressions.tex#L7819 for the picky,
        https://en.cppreference.com/w/cpp/language/operator_other.html for the less patient.

        Asking a question about code? http://eel.is/iso-c++/testcase/

        JonBJ 1 Reply Last reply
        1
        • jeremy_kJ jeremy_k

          @JonB I was going to suggest including a link to the relevant standard section, but attempting to do so myself isn't producing satisfactory results.

          https://github.com/cplusplus/draft/blob/main/source/expressions.tex#L7819 for the picky,
          https://en.cppreference.com/w/cpp/language/operator_other.html for the less patient.

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote last edited by
          #8

          @jeremy_k Thanks. I normally do, this time I actually found that in a long stackoverflow post and just wanted to pick that excerpt.

          1 Reply Last reply
          0
          • Chris KawaC Offline
            Chris KawaC Offline
            Chris Kawa
            Lifetime Qt Champion
            wrote last edited by
            #9

            It is syntactically correct (just an expression of type void), but it's a case of what I would call "clever code" (not a compliment). It lessens readability and kinda hides the real action in a side effect of an operator for the sake of... yeah, being clever I guess, as it's not even shorter or anything.

            Another example of this I've seen is the "clever" use of comma operator:
            std::cout << calculate42(), calculate43();
            Without looking it up - do you remember what gets printed?

            JonBJ S 2 Replies Last reply
            1
            • Chris KawaC Chris Kawa

              It is syntactically correct (just an expression of type void), but it's a case of what I would call "clever code" (not a compliment). It lessens readability and kinda hides the real action in a side effect of an operator for the sake of... yeah, being clever I guess, as it's not even shorter or anything.

              Another example of this I've seen is the "clever" use of comma operator:
              std::cout << calculate42(), calculate43();
              Without looking it up - do you remember what gets printed?

              JonBJ Offline
              JonBJ Offline
              JonB
              wrote last edited by JonB
              #10

              @Chris-Kawa said in Conditional operator as a statement:

              Without looking it up - do you remember what gets printed?

              , operator returns value to right of it, so I would expect to see 1 more than the answer to Life, The Universe & Everything :)

              You can, of course, also implement simple if then else statements with && and ||:

              x && xIsTrue();
              x || xIsFalse();
              x && xIsTrue() || xIsFalse();
              
              Chris KawaC 1 Reply Last reply
              0
              • JonBJ JonB

                @Chris-Kawa said in Conditional operator as a statement:

                Without looking it up - do you remember what gets printed?

                , operator returns value to right of it, so I would expect to see 1 more than the answer to Life, The Universe & Everything :)

                You can, of course, also implement simple if then else statements with && and ||:

                x && xIsTrue();
                x || xIsFalse();
                x && xIsTrue() || xIsFalse();
                
                Chris KawaC Offline
                Chris KawaC Offline
                Chris Kawa
                Lifetime Qt Champion
                wrote last edited by
                #11

                @JonB said in Conditional operator as a statement:

                , operator returns value to right of it, so I would expect to see 1 more than the answer to Life, The Universe & Everything :)

                Gotcha! :) Operator , has lower precedence than operator <<.

                JonBJ 1 Reply Last reply
                0
                • Chris KawaC Chris Kawa

                  @JonB said in Conditional operator as a statement:

                  , operator returns value to right of it, so I would expect to see 1 more than the answer to Life, The Universe & Everything :)

                  Gotcha! :) Operator , has lower precedence than operator <<.

                  JonBJ Offline
                  JonBJ Offline
                  JonB
                  wrote last edited by
                  #12

                  @Chris-Kawa said in Conditional operator as a statement:

                  Gotcha! :) Operator , has lower precedence than operator <<.

                  Ridiculous! I do not acknowledge << "stream" as a decent operator! Does that have different precedence than the only respectable << shift-left operator? :)

                  1 Reply Last reply
                  0
                  • Chris KawaC Offline
                    Chris KawaC Offline
                    Chris Kawa
                    Lifetime Qt Champion
                    wrote last edited by
                    #13

                    With stream and shift operators it's like with right and left angles.
                    They're really the same thing (wink wink, nudge nudge).

                    1 Reply Last reply
                    0
                    • Chris KawaC Chris Kawa

                      It is syntactically correct (just an expression of type void), but it's a case of what I would call "clever code" (not a compliment). It lessens readability and kinda hides the real action in a side effect of an operator for the sake of... yeah, being clever I guess, as it's not even shorter or anything.

                      Another example of this I've seen is the "clever" use of comma operator:
                      std::cout << calculate42(), calculate43();
                      Without looking it up - do you remember what gets printed?

                      S Offline
                      S Offline
                      SimonSchroeder
                      wrote last edited by
                      #14

                      @Chris-Kawa said in Conditional operator as a statement:

                      It is syntactically correct (just an expression of type void), but it's a case of what I would call "clever code" (not a compliment).

                      I would say, in general this has several caveats:

                      1. It works in this case (as described in the OP) because both functions return void.
                      2. If they don't return void (but the same type), there might be a [[maybe_unused]] needed depending on compiler flags.
                      3. If they return incompatible types this doesn't work. (This makes it a programming pattern that cannot always be applied.)

                      For me, it has too many caveats. It's bad for teachability (which to the C++ standards committee is important).

                      It is also one of the use cases for this operator that is not taught. In theory, every C and C++ programmer should be able to figure this out, but it is certainly not beginner friendly. Code is meant to be written once (or at least very few times) but read several times. This will certainly break the reading flow for programmers on every experience level because it is so unusal.

                      The general rule is to never user ?:, but to use regular if/else instead. There are a few corner cases where this is still acceptable. This mostly has to do with initialization. It is kind of unavoidable with const variables (though, there is a workaround with immediately invoked lambdas):

                      const auto myvar = someBool ? 0 : 1;
                      

                      But, even without const we would otherwise have initialization + copy if we are using if/else. The same is true for the OP example:

                      setLabelText(docType == SW::FACTURA ? "Factura" : "Boleta");
                      

                      In this case the QString constructor will only be called for one of the strings.

                      To answer the initial question: I don't think this is acceptable in the broader C++ community.

                      JonBJ 1 Reply Last reply
                      0
                      • S SimonSchroeder

                        @Chris-Kawa said in Conditional operator as a statement:

                        It is syntactically correct (just an expression of type void), but it's a case of what I would call "clever code" (not a compliment).

                        I would say, in general this has several caveats:

                        1. It works in this case (as described in the OP) because both functions return void.
                        2. If they don't return void (but the same type), there might be a [[maybe_unused]] needed depending on compiler flags.
                        3. If they return incompatible types this doesn't work. (This makes it a programming pattern that cannot always be applied.)

                        For me, it has too many caveats. It's bad for teachability (which to the C++ standards committee is important).

                        It is also one of the use cases for this operator that is not taught. In theory, every C and C++ programmer should be able to figure this out, but it is certainly not beginner friendly. Code is meant to be written once (or at least very few times) but read several times. This will certainly break the reading flow for programmers on every experience level because it is so unusal.

                        The general rule is to never user ?:, but to use regular if/else instead. There are a few corner cases where this is still acceptable. This mostly has to do with initialization. It is kind of unavoidable with const variables (though, there is a workaround with immediately invoked lambdas):

                        const auto myvar = someBool ? 0 : 1;
                        

                        But, even without const we would otherwise have initialization + copy if we are using if/else. The same is true for the OP example:

                        setLabelText(docType == SW::FACTURA ? "Factura" : "Boleta");
                        

                        In this case the QString constructor will only be called for one of the strings.

                        To answer the initial question: I don't think this is acceptable in the broader C++ community.

                        JonBJ Offline
                        JonBJ Offline
                        JonB
                        wrote last edited by
                        #15

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

                        jsulmJ J.HilkJ S 3 Replies 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.

                          jsulmJ Offline
                          jsulmJ Offline
                          jsulm
                          Lifetime Qt Champion
                          wrote last edited by
                          #16

                          @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

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

                          JonBJ 1 Reply Last reply
                          0
                          • 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 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 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 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 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 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 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 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 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

                                          • Login

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