Results 1 to 4 of 4
if anyone knows plz explain this conditional operator
timeout ? : MAX SCHEDULE_TIMEOUT...
- 02-24-2010 #1Just Joined!
- Join Date
- Jan 2010
- Posts
- 11
conditional operator in c
if anyone knows plz explain this conditional operator
timeout ? : MAX SCHEDULE_TIMEOUT
- 02-24-2010 #2
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.
- 02-24-2010 #3
I don't know if it's intentional or not, but the syntax that you're using is slightly wrong.
In the following code:
Note that the true result needs to be between the ? and the :, and the false result needs to be after the :.Code:result = (timeout != 0) ? timeout : MAX_SCHEDULE_TIMEOUT
DISTRO=Arch
Registered Linux User #388732
- 02-25-2010 #4
I struggled with the ternary operator too when I was first learning C/C++.
The way I remember it is by thinking:
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 :.Code:IF ? THEN : ELSE


Reply With Quote