- #1
- 2,076
- 140
I noticed some interesting utility in using ? and : when writing some recursive code out of boredom. I thought I'd share some of the code for those interested.
These were written in C, and I must say they simplify a lot of code.
Why is there no initiative for this notation? This code surely must run as fast as possible.
These were written in C, and I must say they simplify a lot of code.
Code:
#include <stdio.h>
#include <math.h>
/* Return x raised to the power n for n >= 0. */
double power(double x, int n){
return n == 0 ? 1 : x * power(x, n-1);
}
/* Return x raised to the power n for n >= 0. This code reduces the recursive calls.*/
double power2(double x, int n){
return n == 0 ? 1 : n % 2 != 0 ? x * power2(x, n/2) * power2(x, n/2) : power2(x, n/2) * power2(x, n/2);
}
/* Return the number of digits in integer n, n >= 0. */
int num_digits(int n){
return n < 10 ? 1 : num_digits(n/10) + 1;
}
/* Return the count of the number of times target occurs in the first
* n elements of array a.
*/
int occurrences(int a[], int n, int target){
return n <= 0 ? 0 : *(a+n-1) == target ? occurrences(a, n-1, target) + 1 : occurrences(a, n-1, target);
}
Why is there no initiative for this notation? This code surely must run as fast as possible.