Ternary operator ((a>b)?a:b) inside return statement?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ratheeshp
    New Member
    • May 2007
    • 1

    Ternary operator ((a>b)?a:b) inside return statement?

    Is it possible to write "return" function inside a conditional operator as shown below?

    a>b? return a: return b;
  • Savage
    Recognized Expert Top Contributor
    • Feb 2007
    • 1759

    #2
    Originally posted by ratheeshp
    Is it possible to write "return" function inside a conditional operator as shown below?

    a>b? return a: return b;
    Yes,but it would be:

    return(a>b)?a:b ;

    Savage

    Comment

    • sicarie
      Recognized Expert Specialist
      • Nov 2006
      • 4677

      #3
      I've changed the title of the thread to better describe the issue - please let me know if you don't think it does (and what you want it to be).

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        Originally posted by ratheeshp
        Is it possible to write "return" function inside a conditional operator as shown below?

        a>b? return a: return b;
        No. If you try this it won't compile.

        The ternary operator requires expressions but not code. You can, however, call a function because the function becomes an instance of its return type so you get the return value from the operator.

        Comment

        • svlsr2000
          Recognized Expert New Member
          • Feb 2007
          • 181

          #5
          Originally posted by weaknessforcats
          No. If you try this it won't compile.

          The ternary operator requires expressions but not code. You can, however, call a function because the function becomes an instance of its return type so you get the return value from the operator.
          But most of the book defines terinary operator as
          Condition ? expression 1: exression 2;

          My doubt : Is return statement is a expression or not.

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by svlsr2000
            how about a>b?return a; return b;
            That won't work; 'return' is a statement and the ternary operator ?: wants
            expressions. It just won't compile.

            kind regards,

            Jos

            Comment

            • svlsr2000
              Recognized Expert New Member
              • Feb 2007
              • 181

              #7
              Originally posted by JosAH
              That won't work; 'return' is a statement and the ternary operator ?: wants
              expressions. It just won't compile.

              kind regards,

              Jos
              Oh i got it, i think i really need a long break during this weekend. :)

              Comment

              Working...