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.(adsbygoogle = window.adsbygoogle || []).push({});

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.Code (Text):

#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);

}

**Physics Forums - The Fusion of Science and Community**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# [C] The usage of ? and : when cleaning up recursive code

Loading...

Similar Threads - usage cleaning recursive | Date |
---|---|

Python MITx edx 6.00.2x python 2 code, need to fix a bug | Apr 17, 2016 |

[C++] Any suggestions on how to clean up this procedure? | Nov 23, 2014 |

Understanding List of Methids and its Usage in User-32 DLL | Mar 29, 2013 |

Scientific computing and efficient memory usage | Dec 23, 2011 |

CPU usage | Nov 22, 2010 |

**Physics Forums - The Fusion of Science and Community**