听到有人说,if/else比三目运算符? :容易调试,而且可读性高、效率也高( ⊙o⊙ )?!我迅速地搜索?:还有没有存在的理由,难道我一直都在写着晦涩、低效的? : !?为了一探究竟,我写下了这段代码:
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> int main() { int a = 1, b = 2, c; if(a < b) c = a; else c = b; c = a < b ? a : b; return 0; } |
g++ test.cpp -S 得到:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | call ___main movl $1,-4(%ebp) ; a movl $2,-8(%ebp) ; b movl -4(%ebp),%eax ;if/else开始 cmpl -8(%ebp),%eax jge L2 movl -4(%ebp),%eax movl %eax,-12(%ebp) jmp L3 .p2align 4,,7 L2: movl -8(%ebp),%eax movl %eax,-12(%ebp) ; if/else结束 L3: movl -8(%ebp),%eax ; ? :开始 cmpl -4(%ebp),%eax jle L4 movl -4(%ebp),%eax L4: movl %eax,-12(%ebp) ; ? :结束 |
if/else用了8条指令,?:用了5条,这个差距可不算小了啊!因为,程序里面是要有循环的,多数循环里面会有分支语句,且很多情况下是二分支。
呃……又学到一个单词,ternary:三元。:-)
你好!除了代码,此处没有多少原创之物,皆为本人搜集、整理、总结之记录与心得,欢迎转载分享!转载时请尽量注明出处,将不胜感激。祝你健康、快乐!
Be the first to comment on this entry.