Reference: http://blog.csdn.net/speedme/article/details/22916181
1. & judgment features
#include <stdio.h>int sumf(int i){ int sum = 0;#if 0 i && (sum = i+ sumf(i-1));#else if(i!=0){ sum = i+ sumf(i-1); }#endif return sum; }int main(){ printf("sum(%d)=%d\n",4,sumf(4)); printf("aaaaaaaaaaaa\n");}
Compiled with GCC, it seems that if statements are more efficient.
sumf:// if(i!=0){ sum = i+ sumf(i-1); }
pushl %ebp movl %esp, %ebp subl $40, %esp movl $0, -12(%ebp) cmpl $0, 8(%ebp) je .L2 movl 8(%ebp), %eax subl $1, %eax movl %eax, (%esp) call sumf addl 8(%ebp), %eax movl %eax, -12(%ebp).L2: movl -12(%ebp), %eax leave ret
sumf://i && (sum = i+ sumf(i-1));
pushl %ebp movl %esp, %ebp subl $40, %esp movl $0, -12(%ebp) cmpl $0, 8(%ebp) je .L3 movl 8(%ebp), %eax subl $1, %eax movl %eax, (%esp) call sumf addl 8(%ebp), %eax movl %eax, -12(%ebp) cmpl $0, -12(%ebp).L3: movl -12(%ebp), %eax leave ret
2. Alternative Iteration Methods :::::(! Is more practical)
# Include <stdio. h> typedef unsigned int (* Fun) (unsigned INT); unsigned int solution3_teminator (unsigned int N) {return 0;} unsigned int sum_solution3 (unsigned int N) {static Fun f [2] = {solution3_teminator, sum_solution3}; return N + F [!! N] (N-1); // note here} int sumf (int I) {int sum = 0; # If 0 I & (sum = I + sumf (I-1); # else if (I! = 0) {sum = I + sumf (I-1);} # endif return sum;} int main () {printf ("sum_solution3 (% d) = % d \ n ", 4, sum_solution3 (4); printf ("sum (% d) = % d \ n", 4, sumf (4 )); printf ("aaaaaaaaaaaa \ n ");}
Use the operator feature to replace the if judgment statement