Find the answer to your Linux question:
Results 1 to 4 of 4
if anyone knows plz explain this conditional operator timeout ? : MAX SCHEDULE_TIMEOUT...
  1. #1
    Just Joined!
    Join Date
    Jan 2010
    Posts
    11

    Post conditional operator in c

    if anyone knows plz explain this conditional operator
    timeout ? : MAX SCHEDULE_TIMEOUT

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    This operator (?) is somewhat special, because it is "ternary". Most operators are unary or binary.
    Unary means the operator works on one argument. Like a++ increments a, and only a, by one.
    Binary operators do work with two arguments. Like (+) in 4+3. This would give you a 7 as "result".

    This operator has three arguments. Let's call them #1, #2, #3. What the ? does is:
    The result of (#1 ? #2 #3) is: #2 if #1 is "true", #3 if #1 is "false".

    You will understand it better if you assign the value to some variable.
    result = timeout ? : MAX SCHEDULE_TIMEOUT;
    This is a short form of
    Code:
    if (timeout) 
      result = MAX;
    else
      result = SCHEDULE_TIMEOUT;
    Debian GNU/Linux -- You know you want it.

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    I don't know if it's intentional or not, but the syntax that you're using is slightly wrong.

    In the following code:
    Code:
    result = (timeout != 0) ? timeout : MAX_SCHEDULE_TIMEOUT
    Note that the true result needs to be between the ? and the :, and the false result needs to be after the :.
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Just Joined! KPolulak's Avatar
    Join Date
    Feb 2009
    Location
    New Jersey, USA
    Posts
    42
    I struggled with the ternary operator too when I was first learning C/C++.

    The way I remember it is by thinking:

    Code:
    IF ? THEN : ELSE
    Also, if you have trouble remembering which symbol comes first, the ? or the :, then think of the statement as a question. "What if?" You'll remember that it's ? then :.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...