I read everywhere that ternary operator is supposed to be faster than, or at least the same as, its equivalent if-else block.
However, I di
The assembler code generated will tell the story:
a = (b > c) ? 1 : 0;
Generates:
mov edx, DWORD PTR a[rip]
mov eax, DWORD PTR b[rip]
cmp edx, eax
setg al
Whereas:
if (a > b) printf("a");
else printf("b");
Generates:
mov edx, DWORD PTR a[rip]
mov eax, DWORD PTR b[rip]
cmp edx, eax
jle .L4
;printf a
jmp .L5
.L4:
;printf b
.L5:
So the ternary can be shorter and faster simply due to using fewer instructions and no jumps if you are looking for true/false. If you use values other than 1 and 0, you will get the same code as an if/else, for example:
a = (b > c) ? 2 : 3;
Generates:
mov edx, DWORD PTR b[rip]
mov eax, DWORD PTR c[rip]
cmp edx, eax
jle .L6
mov eax, 2
jmp .L7
.L6:
mov eax, 3
.L7:
Which is the same as the if/else.