I do not understand the termination parameter of this for loop. What does it mean? Specifically, what do the ?, ->, and : 0 represent?
for( i = 0; i < (sequence ? sequence->total : 0); i++ )
I do not understand the termination parameter of this for loop. What does it mean? Specifically, what do the ?, ->, and : 0 represent?
for( i = 0; i < (sequence ? sequence->total : 0); i++ )
This: (sequence ? sequence->total : 0)
(it's called a "ternary if", since it takes three inputs) is like saying:
if (sequence)
replaceEntireExpressionWith(sequence->total);
else
replaceEntireExpressionWith(0);
->
is a dereferencer, just like *
, but it makes user data-types like struct
s easy to use.
sequence->total
means sequence
is a pointer to a one of those data types, and you are accessing the total
property of what it is pointing to. It's exactly the same as:
(*sequence).total;
So the loop:
for( i = 0; i < (sequence ? sequence->total : 0); i++ )
exits when sequence
evaluates to false
, since 0 == false
.
The ternary if construction is used to make sure they aren't dereferencing (->
) a null pointer, because if they just put sequence->total
as the condition, they would be dereferencing it every time. Unhappy! =(
if sequence not valid, or is the member called "total" is reached by i.
The ? says if sequence is not valid the loop ends when i = 0. (so it wont run)
You're seeing two different operators.
The conditional operator
condition ? truePart : falsePart
This operator check whether condition
is true, and evaluates to either truePart
or falsePart
.
The deferenced member operator
pointer->member
This is equivalent to (*pointer).member
.
Your expression will evaluate to 0
if sequence
is null, and the total
property of the structure that sequence
points to if it isn't null.
there are two things at work here:
the ? and : syntax are the syntax for a ternary operation
http://en.wikipedia.org/wiki/Ternary_operation
other answers here explain ternary operators concisely
the -> syntax is to access a member from a pointer as opposed to a reference or value
this code is equivalent to:
int total = 0;
if(sequence){
total = sequence->total;
}
for( i=0; i < total; ++i){
...
}
? : is the ternary operator. It evaluates the expression before the ?, and the result is the expression after the ? if true, or the expression after the : if false.
-> is what I'd call "operator arrow", but what it essentially does is dereference the pointer sequence
, and then access a member called total
.
Two things here:
sequence
is not a NULL
pointer before attempting to dereference it with ->
,for( i = 0; sequence && i < sequence->total; i++ )