I have a simple doubt about the flow of the below code snippet. I compare this code block both on the high level and assembly instruction level. And I found that ?:
is far better than branching.
const int THUMB_IMAGE = 0;
const int ICON_IMAGE = 1;
const int UNKNOWN_IMAGE = 2;
void foo( int nFlag ){
int CopyFlag = nFlag;
if( CopyFlag == THUMB_IMAGE )
CopyFLag = ICON_IMAGE; // Setting THUMB and ICON images to same level
// Executing rest of the code
}
void foo1( int nFlag ){
int CopyFlag = ( nFlag == THUMB_IMAGE ) ?
ICON_IMAGE : nFlag; // Setting THUMB and ICON images to same level
// Executing rest of the code
}
int main(void){
foo( THUMB_IMAGE );
foo1( THUMB_IMAGE );
return 0;
}
In the above code snippet, there are two functions, foo()
and foo1()
. These two functions are setting two image types to ICON_IMAGE
.
The question is how the assignment and if()
are implemented?
Which conditional statements are highly optimized, if()
or ternary operator ?:
?
On the assembly code level, to translate the if()
, CMP
(branch) and MOV
instructions are necessary.
And for the ?:
operator, I think there are some special instructions but the branch instruction is completely avoided.
Can anyone tell which is the best method?
In foo()
, the very first an assignment operation is done regardless of the if condition. It may not be needed all the time.
But in foo1()
, this is done in the ?:
operator section and avoids the unwanted assignment operation. I want to know if the code in foo()
or foo1()
respectively, is optimized?